diff options
Diffstat (limited to 'src')
660 files changed, 27642 insertions, 16832 deletions
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 8dee99c65e7..0428738f2dd 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -8,42 +8,33 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -if( USE_COREPCH ) - include_directories(${CMAKE_CURRENT_BINARY_DIR}) -endif() - -file(GLOB_RECURSE sources_Common Common.cpp Common.h) -file(GLOB_RECURSE sources_Collision Collision/*.cpp Collision/*.h) -file(GLOB_RECURSE sources_Threading Threading/*.cpp Threading/*.h) -file(GLOB_RECURSE sources_Utilities Utilities/*.cpp Utilities/*.h) -file(GLOB_RECURSE sources_Configuration Configuration/*.cpp Configuration/*.h) -file(GLOB_RECURSE sources_Logging Logging/*.cpp Logging/*.h) -if (SERVERS) - file(GLOB_RECURSE sources_Cryptography Cryptography/*.cpp Cryptography/*.h) -endif (SERVERS) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/Debugging + ${CMAKE_CURRENT_SOURCE_DIR}/Platform + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) # Manually set sources for Debugging directory as we don't want to include WheatyExceptionReport in common project # It needs to be included both in authserver and worldserver for the static global variable to be properly initialized # and to handle crash logs on windows -set(sources_Debugging Debugging/Errors.cpp Debugging/Errors.h) -file(GLOB sources_localdir *.cpp *.h) +list(APPEND PRIVATE_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/Debugging/Errors.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Debugging/Errors.h) if (USE_COREPCH) - set(common_STAT_PCH_HDR PrecompiledHeaders/commonPCH.h) - set(common_STAT_PCH_SRC PrecompiledHeaders/commonPCH.cpp) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/commonPCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/commonPCH.cpp) endif (USE_COREPCH) -set(common_STAT_SRCS - ${common_STAT_SRCS} - ${sources_Common} - ${sources_Collision} - ${sources_Threading} - ${sources_Utilities} - ${sources_Debugging} - ${sources_Configuration} - ${sources_Logging} - ${sources_Cryptography} - ${sources_localdir} +GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) + +add_definitions(-DTRINITY_API_EXPORT_COMMON) + +add_library(common + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES} ) # Do NOT add any extra include directory here, as we don't want the common @@ -55,37 +46,55 @@ set(common_STAT_SRCS # linkage (enums, defines...) it is discouraged to do so unless necessary, as it will pullute # include_directories leading to further unnoticed dependency aditions # Linker Depencency requirements: none -include_directories( - ${CMAKE_BINARY_DIR} +CollectIncludeDirectories( ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/Collision - ${CMAKE_CURRENT_SOURCE_DIR}/Collision/Management - ${CMAKE_CURRENT_SOURCE_DIR}/Collision/Maps - ${CMAKE_CURRENT_SOURCE_DIR}/Collision/Models - ${CMAKE_CURRENT_SOURCE_DIR}/Configuration - ${CMAKE_CURRENT_SOURCE_DIR}/Cryptography - ${CMAKE_CURRENT_SOURCE_DIR}/Debugging - ${CMAKE_CURRENT_SOURCE_DIR}/Logging - ${CMAKE_CURRENT_SOURCE_DIR}/Utilities - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour/Include - ${CMAKE_SOURCE_DIR}/dep/SFMT - ${CMAKE_SOURCE_DIR}/dep/utf8cpp - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) -GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(common + PUBLIC + # Provide the binary dir for all child targets + ${CMAKE_BINARY_DIR} + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) -add_library(common STATIC - ${common_STAT_SRCS} - ${common_STAT_PCH_SRC} -) +target_link_libraries(common + PUBLIC + boost + cppformat + g3dlib + Detour + sfmt + utf8cpp + openssl + valgrind + threads + jemalloc + PRIVATE + process) add_dependencies(common revision_data.h) +set_target_properties(common + PROPERTIES + FOLDER + "server") + +if( BUILD_SHARED_LIBS ) + if( UNIX ) + install(TARGETS common + LIBRARY + DESTINATION lib) + elseif( WIN32 ) + install(TARGETS common + RUNTIME + DESTINATION "${CMAKE_INSTALL_PREFIX}") + endif() +endif() + # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(common ${common_STAT_PCH_HDR} ${common_STAT_PCH_SRC}) + add_cxx_pch(common ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif () diff --git a/src/common/Collision/BoundingIntervalHierarchy.h b/src/common/Collision/BoundingIntervalHierarchy.h index 0b15bd2d92f..d84ee3f6bf3 100644 --- a/src/common/Collision/BoundingIntervalHierarchy.h +++ b/src/common/Collision/BoundingIntervalHierarchy.h @@ -67,7 +67,7 @@ struct AABound Copyright (c) 2003-2007 Christopher Kulla */ -class BIH +class TC_COMMON_API BIH { private: void init_empty() @@ -91,7 +91,7 @@ class BIH buildData dat; dat.maxPrims = leafSize; - dat.numPrims = primitives.size(); + dat.numPrims = uint32(primitives.size()); dat.indices = new uint32[dat.numPrims]; dat.primBound = new G3D::AABox[dat.numPrims]; getBounds(primitives[0], bounds); @@ -115,7 +115,7 @@ class BIH delete[] dat.primBound; delete[] dat.indices; } - uint32 primCount() const { return objects.size(); } + uint32 primCount() const { return uint32(objects.size()); } template<typename RayCallback> void intersectRay(const G3D::Ray &r, RayCallback& intersectCallback, float &maxDist, bool stopAtFirst=false) const diff --git a/src/common/Collision/DynamicTree.cpp b/src/common/Collision/DynamicTree.cpp index 5d2e18b1a2e..111606644de 100644 --- a/src/common/Collision/DynamicTree.cpp +++ b/src/common/Collision/DynamicTree.cpp @@ -248,7 +248,7 @@ bool DynamicMapTree::isInLineOfSight(float x1, float y1, float z1, float x2, flo float DynamicMapTree::getHeight(float x, float y, float z, float maxSearchDist, uint32 phasemask) const { - G3D::Vector3 v(x, y, z); + G3D::Vector3 v(x, y, z + 0.5f); G3D::Ray r(v, G3D::Vector3(0, 0, -1)); DynamicTreeIntersectionCallback callback(phasemask); impl->intersectZAllignedRay(r, callback, maxSearchDist); diff --git a/src/common/Collision/DynamicTree.h b/src/common/Collision/DynamicTree.h index 0f18bb265f8..85707efebd2 100644 --- a/src/common/Collision/DynamicTree.h +++ b/src/common/Collision/DynamicTree.h @@ -31,7 +31,7 @@ namespace G3D class GameObjectModel; struct DynTreeImpl; -class DynamicMapTree +class TC_COMMON_API DynamicMapTree { DynTreeImpl *impl; diff --git a/src/common/Collision/Management/IVMapManager.h b/src/common/Collision/Management/IVMapManager.h index 1e64551956c..35437b7b816 100644 --- a/src/common/Collision/Management/IVMapManager.h +++ b/src/common/Collision/Management/IVMapManager.h @@ -42,7 +42,7 @@ namespace VMAP #define VMAP_INVALID_HEIGHT_VALUE -200000.0f // real assigned value in unknown height case //=========================================================== - class IVMapManager + class TC_COMMON_API IVMapManager { private: bool iEnableLineOfSightCalc; diff --git a/src/common/Collision/Management/MMapFactory.h b/src/common/Collision/Management/MMapFactory.h index edd074fc93d..f89f44ba4df 100644 --- a/src/common/Collision/Management/MMapFactory.h +++ b/src/common/Collision/Management/MMapFactory.h @@ -38,12 +38,11 @@ namespace MMAP // static class // holds all mmap global data // access point to MMapManager singleton - class MMapFactory + class TC_COMMON_API MMapFactory { public: static MMapManager* createOrGetMMapManager(); static void clear(); - static bool IsPathfindingEnabled(uint32 mapId); }; } diff --git a/src/common/Collision/Management/MMapManager.cpp b/src/common/Collision/Management/MMapManager.cpp index 04b1e62399b..66808e08e34 100644 --- a/src/common/Collision/Management/MMapManager.cpp +++ b/src/common/Collision/Management/MMapManager.cpp @@ -23,6 +23,9 @@ 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"; + // ######################## MMapManager ######################## MMapManager::~MMapManager() { @@ -70,26 +73,20 @@ namespace MMAP } // load and init dtNavMesh - read parameters from file - std::string dataDir = sConfigMgr->GetStringDefault("DataDir", "./"); - uint32 pathLen = dataDir.length() + strlen("/mmaps/%03i.mmap") + 1; - char *fileName = new char[pathLen]; - snprintf(fileName, pathLen, (dataDir + "/mmaps/%03i.mmap").c_str(), mapId); - - FILE* file = fopen(fileName, "rb"); + std::string fileName = Trinity::StringFormat(MAP_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", ".").c_str(), mapId); + FILE* file = fopen(fileName.c_str(), "rb"); if (!file) { - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not open mmap file '%s'", fileName); - delete [] fileName; + TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not open mmap file '%s'", fileName.c_str()); return false; } dtNavMeshParams params; - int count = fread(¶ms, sizeof(dtNavMeshParams), 1, file); + uint32 count = uint32(fread(¶ms, sizeof(dtNavMeshParams), 1, file)); fclose(file); if (count != 1) { - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not read params from file '%s'", fileName); - delete [] fileName; + TC_LOG_DEBUG("maps", "MMAP:loadMapData: Error: Could not read params from file '%s'", fileName.c_str()); return false; } @@ -98,18 +95,14 @@ 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); - delete [] fileName; + TC_LOG_ERROR("maps", "MMAP:loadMapData: Failed to initialize dtNavMesh for mmap %03u from file %s", mapId, fileName.c_str()); return false; } - delete [] fileName; - TC_LOG_DEBUG("maps", "MMAP:loadMapData: Loaded %03i.mmap", mapId); // store inside our map list MMapData* mmap_data = new MMapData(mesh); - mmap_data->mmapLoadedTiles.clear(); itr->second = mmap_data; return true; @@ -120,7 +113,7 @@ namespace MMAP return uint32(x << 16 | y); } - bool MMapManager::loadMap(const std::string& basePath, uint32 mapId, int32 x, int32 y) + bool MMapManager::loadMap(const std::string& /*basePath*/, uint32 mapId, int32 x, int32 y) { // make sure the mmap is loaded and ready to load tiles if (!loadMapData(mapId)) @@ -132,23 +125,17 @@ namespace MMAP // check if we already have this tile loaded uint32 packedGridPos = packTileID(x, y); - if (mmap->mmapLoadedTiles.find(packedGridPos) != mmap->mmapLoadedTiles.end()) + if (mmap->loadedTileRefs.find(packedGridPos) != mmap->loadedTileRefs.end()) return false; // load this tile :: mmaps/MMMXXYY.mmtile - uint32 pathLen = basePath.length() + strlen("/%03i%02i%02i.mmtile") + 1; - char *fileName = new char[pathLen]; - - snprintf(fileName, pathLen, (basePath + "/%03i%02i%02i.mmtile").c_str(), mapId, x, y); - - FILE* file = fopen(fileName, "rb"); + std::string fileName = Trinity::StringFormat(TILE_FILE_NAME_FORMAT, sConfigMgr->GetStringDefault("DataDir", ".").c_str(), 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); - delete [] fileName; + TC_LOG_DEBUG("maps", "MMAP:loadMap: Could not open mmtile file '%s'", fileName.c_str()); return false; } - delete [] fileName; // read header MmapTileHeader fileHeader; @@ -186,7 +173,7 @@ namespace MMAP // memory allocated for data is now managed by detour, and will be deallocated when the tile is removed if (dtStatusSucceed(mmap->navMesh->addTile(data, fileHeader.size, DT_TILE_FREE_DATA, 0, &tileRef))) { - mmap->mmapLoadedTiles.insert(std::pair<uint32, dtTileRef>(packedGridPos, tileRef)); + 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); return true; @@ -214,14 +201,14 @@ namespace MMAP // check if we have this tile loaded uint32 packedGridPos = packTileID(x, y); - if (mmap->mmapLoadedTiles.find(packedGridPos) == mmap->mmapLoadedTiles.end()) + 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); return false; } - dtTileRef tileRef = mmap->mmapLoadedTiles[packedGridPos]; + dtTileRef tileRef = mmap->loadedTileRefs[packedGridPos]; // unload, and mark as non loaded if (dtStatusFailed(mmap->navMesh->removeTile(tileRef, NULL, NULL))) @@ -234,7 +221,7 @@ namespace MMAP } else { - mmap->mmapLoadedTiles.erase(packedGridPos); + mmap->loadedTileRefs.erase(packedGridPos); --loadedTiles; TC_LOG_DEBUG("maps", "MMAP:unloadMap: Unloaded mmtile %03i[%02i, %02i] from %03i", mapId, x, y, mapId); return true; @@ -255,7 +242,7 @@ namespace MMAP // unload all tiles from given map MMapData* mmap = itr->second; - for (MMapTileSet::iterator i = mmap->mmapLoadedTiles.begin(); i != mmap->mmapLoadedTiles.end(); ++i) + for (MMapTileSet::iterator i = mmap->loadedTileRefs.begin(); i != mmap->loadedTileRefs.end(); ++i) { uint32 x = (i->first >> 16); uint32 y = (i->first & 0x0000FFFF); diff --git a/src/common/Collision/Management/MMapManager.h b/src/common/Collision/Management/MMapManager.h index 1a502a916dd..0b85351f6a5 100644 --- a/src/common/Collision/Management/MMapManager.h +++ b/src/common/Collision/Management/MMapManager.h @@ -22,7 +22,6 @@ #include "Define.h" #include "DetourNavMesh.h" #include "DetourNavMeshQuery.h" - #include <string> #include <unordered_map> #include <vector> @@ -46,11 +45,11 @@ namespace MMAP dtFreeNavMesh(navMesh); } - dtNavMesh* navMesh; - // we have to use single dtNavMeshQuery for every instance, since those are not thread safe NavMeshQuerySet navMeshQueries; // instanceId to query - MMapTileSet mmapLoadedTiles; // maps [map grid coords] to [dtTile] + + dtNavMesh* navMesh; + MMapTileSet loadedTileRefs; // maps [map grid coords] to [dtTile] }; @@ -58,7 +57,7 @@ namespace MMAP // singleton class // holds all all access to mmap loading unloading and meshes - class MMapManager + class TC_COMMON_API MMapManager { public: MMapManager() : loadedTiles(0), thread_safe_environment(true) {} @@ -75,7 +74,7 @@ namespace MMAP dtNavMesh const* GetNavMesh(uint32 mapId); uint32 getLoadedTilesCount() const { return loadedTiles; } - uint32 getLoadedMapsCount() const { return loadedMMaps.size(); } + uint32 getLoadedMapsCount() const { return uint32(loadedMMaps.size()); } private: bool loadMapData(uint32 mapId); uint32 packTileID(int32 x, int32 y); diff --git a/src/common/Collision/Management/VMapFactory.h b/src/common/Collision/Management/VMapFactory.h index 1a45bd5094b..a730fa12ef2 100644 --- a/src/common/Collision/Management/VMapFactory.h +++ b/src/common/Collision/Management/VMapFactory.h @@ -29,7 +29,7 @@ namespace VMAP { //=========================================================== - class VMapFactory + class TC_COMMON_API VMapFactory { public: static IVMapManager* createOrGetVMapManager(); diff --git a/src/common/Collision/Management/VMapManager2.h b/src/common/Collision/Management/VMapManager2.h index 722ac4935c6..61c5025e41f 100644 --- a/src/common/Collision/Management/VMapManager2.h +++ b/src/common/Collision/Management/VMapManager2.h @@ -51,7 +51,7 @@ namespace VMAP class StaticMapTree; class WorldModel; - class ManagedModel + class TC_COMMON_API ManagedModel { public: ManagedModel() : iModel(nullptr), iRefCount(0) { } @@ -75,7 +75,7 @@ namespace VMAP VMAP_DISABLE_LIQUIDSTATUS = 0x8 }; - class VMapManager2 : public IVMapManager + class TC_COMMON_API VMapManager2 : public IVMapManager { protected: // Tree to check collision diff --git a/src/common/Collision/Maps/MapDefines.h b/src/common/Collision/Maps/MapDefines.h index 538a78a38d4..a523b0c0186 100644 --- a/src/common/Collision/Maps/MapDefines.h +++ b/src/common/Collision/Maps/MapDefines.h @@ -33,4 +33,4 @@ enum NavTerrain // we only have 8 bits }; -#endif +#endif /* _MAPDEFINES_H */ diff --git a/src/common/Collision/Maps/MapTree.cpp b/src/common/Collision/Maps/MapTree.cpp index 4d0996e1961..5907971efb9 100644 --- a/src/common/Collision/Maps/MapTree.cpp +++ b/src/common/Collision/Maps/MapTree.cpp @@ -22,6 +22,7 @@ #include "VMapDefinitions.h" #include "Log.h" #include "Errors.h" +#include "Metric.h" #include <string> #include <sstream> @@ -415,6 +416,8 @@ namespace VMAP } else iLoadedTiles[packTileID(tileX, tileY)] = false; + TC_METRIC_EVENT("map_events", "LoadMapTile", + "Map: " + std::to_string(iMapID) + " TileX: " + std::to_string(tileX) + " TileY: " + std::to_string(tileY)); return result; } @@ -473,6 +476,8 @@ namespace VMAP } } iLoadedTiles.erase(tile); + TC_METRIC_EVENT("map_events", "UnloadMapTile", + "Map: " + std::to_string(iMapID) + " TileX: " + std::to_string(tileX) + " TileY: " + std::to_string(tileY)); } void StaticMapTree::getModelInstances(ModelInstance* &models, uint32 &count) diff --git a/src/common/Collision/Maps/MapTree.h b/src/common/Collision/Maps/MapTree.h index 63d542754c1..0227a982b4c 100644 --- a/src/common/Collision/Maps/MapTree.h +++ b/src/common/Collision/Maps/MapTree.h @@ -29,7 +29,7 @@ namespace VMAP class GroupModel; class VMapManager2; - struct LocationInfo + struct TC_COMMON_API LocationInfo { LocationInfo(): hitInstance(nullptr), hitModel(nullptr), ground_Z(-G3D::finf()) { } const ModelInstance* hitInstance; @@ -37,7 +37,7 @@ namespace VMAP float ground_Z; }; - class StaticMapTree + class TC_COMMON_API StaticMapTree { typedef std::unordered_map<uint32, bool> loadedTileMap; typedef std::unordered_map<uint32, uint32> loadedSpawnMap; @@ -79,7 +79,7 @@ namespace VMAP bool LoadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm); void UnloadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm); bool isTiled() const { return iIsTiled; } - uint32 numLoadedTiles() const { return iLoadedTiles.size(); } + uint32 numLoadedTiles() const { return uint32(iLoadedTiles.size()); } void getModelInstances(ModelInstance* &models, uint32 &count); private: @@ -87,7 +87,7 @@ namespace VMAP StaticMapTree& operator=(StaticMapTree const& right) = delete; }; - struct AreaInfo + struct TC_COMMON_API AreaInfo { AreaInfo(): result(false), ground_Z(-G3D::finf()), flags(0), adtId(0), rootId(0), groupId(0) { } diff --git a/src/common/Collision/Maps/TileAssembler.cpp b/src/common/Collision/Maps/TileAssembler.cpp index 3f58b8f3516..7ee9125a5c5 100644 --- a/src/common/Collision/Maps/TileAssembler.cpp +++ b/src/common/Collision/Maps/TileAssembler.cpp @@ -355,10 +355,13 @@ namespace VMAP uint32 name_length, displayId; char buff[500]; - while (!feof(model_list)) + while (true) { - if (fread(&displayId, sizeof(uint32), 1, model_list) != 1 - || fread(&name_length, sizeof(uint32), 1, model_list) != 1 + if (fread(&displayId, sizeof(uint32), 1, model_list) != 1) + if (feof(model_list)) // EOF flag is only set after failed reading attempt + break; + + if (fread(&name_length, sizeof(uint32), 1, model_list) != 1 || name_length >= sizeof(buff) || fread(&buff, sizeof(char), name_length, model_list) != name_length) { @@ -369,7 +372,7 @@ namespace VMAP std::string model_name(buff, name_length); WorldModel_Raw raw_model; - if ( !raw_model.Read((iSrcDir + "/" + model_name).c_str()) ) + if (!raw_model.Read((iSrcDir + "/" + model_name).c_str()) ) continue; spawnedModelFiles.insert(model_name); @@ -412,13 +415,14 @@ namespace VMAP fclose(model_list); fclose(model_list_copy); } - // temporary use defines to simplify read/check code (close file and return at fail) - #define READ_OR_RETURN(V, S) if (fread((V), (S), 1, rf) != 1) { \ - fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); } - #define READ_OR_RETURN_WITH_DELETE(V, S) if (fread((V), (S), 1, rf) != 1) { \ - fclose(rf); printf("readfail, op = %i\n", readOperation); delete[] V; return(false); }; - #define CMP_OR_RETURN(V, S) if (strcmp((V), (S)) != 0) { \ - fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); } + +// temporary use defines to simplify read/check code (close file and return at fail) +#define READ_OR_RETURN(V, S) if (fread((V), (S), 1, rf) != 1) { \ + fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); } +#define READ_OR_RETURN_WITH_DELETE(V, S) if (fread((V), (S), 1, rf) != 1) { \ + fclose(rf); printf("readfail, op = %i\n", readOperation); delete[] V; return(false); }; +#define CMP_OR_RETURN(V, S) if (strcmp((V), (S)) != 0) { \ + fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); } bool GroupModel_Raw::Read(FILE* rf) { diff --git a/src/common/Collision/Maps/TileAssembler.h b/src/common/Collision/Maps/TileAssembler.h index 1e2dc1924f1..74111f69910 100644 --- a/src/common/Collision/Maps/TileAssembler.h +++ b/src/common/Collision/Maps/TileAssembler.h @@ -35,7 +35,7 @@ namespace VMAP */ //=============================================== - class ModelPosition + class TC_COMMON_API ModelPosition { private: G3D::Matrix3 iRotation; @@ -55,7 +55,7 @@ namespace VMAP typedef std::map<uint32, ModelSpawn> UniqueEntryMap; typedef std::multimap<uint32, uint32> TileMap; - struct MapSpawns + struct TC_COMMON_API MapSpawns { UniqueEntryMap UniqueEntries; TileMap TileEntries; @@ -64,7 +64,7 @@ namespace VMAP typedef std::map<uint32, MapSpawns*> MapData; //=============================================== - struct GroupModel_Raw + struct TC_COMMON_API GroupModel_Raw { uint32 mogpflags; uint32 GroupWMOID; @@ -82,7 +82,7 @@ namespace VMAP bool Read(FILE* f); }; - struct WorldModel_Raw + struct TC_COMMON_API WorldModel_Raw { uint32 RootWMOID; std::vector<GroupModel_Raw> groupsArray; @@ -90,7 +90,7 @@ namespace VMAP bool Read(const char * path); }; - class TileAssembler + class TC_COMMON_API TileAssembler { private: std::string iDestDir; diff --git a/src/common/Collision/Models/GameObjectModel.h b/src/common/Collision/Models/GameObjectModel.h index 9d8687233c1..37f11af20ac 100644 --- a/src/common/Collision/Models/GameObjectModel.h +++ b/src/common/Collision/Models/GameObjectModel.h @@ -35,7 +35,7 @@ namespace VMAP class GameObject; struct GameObjectDisplayInfoEntry; -class GameObjectModelOwnerBase +class TC_COMMON_API GameObjectModelOwnerBase { public: virtual bool IsSpawned() const { return false; } @@ -47,7 +47,7 @@ public: virtual void DebugVisualizeCorner(G3D::Vector3 const& /*corner*/) const { } }; -class GameObjectModel /*, public Intersectable*/ +class TC_COMMON_API GameObjectModel /*, public Intersectable*/ { GameObjectModel() : phasemask(0), iInvScale(0), iScale(0), iModel(NULL) { } public: @@ -84,4 +84,6 @@ private: std::unique_ptr<GameObjectModelOwnerBase> owner; }; +TC_COMMON_API void LoadGameObjectModelList(std::string const& dataPath); + #endif // _GAMEOBJECT_MODEL_H diff --git a/src/common/Collision/Models/ModelInstance.h b/src/common/Collision/Models/ModelInstance.h index d101630d1e9..84a41b15ce6 100644 --- a/src/common/Collision/Models/ModelInstance.h +++ b/src/common/Collision/Models/ModelInstance.h @@ -39,7 +39,7 @@ namespace VMAP MOD_HAS_BOUND = 1<<2 }; - class ModelSpawn + class TC_COMMON_API ModelSpawn { public: //mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, Bound_lo, Bound_hi, name @@ -60,7 +60,7 @@ namespace VMAP static bool writeToFile(FILE* rw, const ModelSpawn &spawn); }; - class ModelInstance: public ModelSpawn + class TC_COMMON_API ModelInstance: public ModelSpawn { public: ModelInstance(): iInvScale(0.0f), iModel(nullptr) { } diff --git a/src/common/Collision/Models/WorldModel.h b/src/common/Collision/Models/WorldModel.h index 39787f6c664..bfc0367627f 100644 --- a/src/common/Collision/Models/WorldModel.h +++ b/src/common/Collision/Models/WorldModel.h @@ -33,7 +33,7 @@ namespace VMAP struct AreaInfo; struct LocationInfo; - class MeshTriangle + class TC_COMMON_API MeshTriangle { public: MeshTriangle() : idx0(0), idx1(0), idx2(0) { } @@ -44,7 +44,7 @@ namespace VMAP uint32 idx2; }; - class WmoLiquid + class TC_COMMON_API WmoLiquid { public: WmoLiquid(uint32 width, uint32 height, const G3D::Vector3 &corner, uint32 type); @@ -70,7 +70,7 @@ namespace VMAP }; /*! holding additional info for WMO group files */ - class GroupModel + class TC_COMMON_API GroupModel { public: GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(NULL) { } @@ -103,7 +103,7 @@ namespace VMAP }; /*! Holds a model (converted M2 or WMO) in its original coordinate space */ - class WorldModel + class TC_COMMON_API WorldModel { public: WorldModel(): RootWMOID(0) { } diff --git a/src/common/Collision/RegularGrid.h b/src/common/Collision/RegularGrid.h index 6a2a07968ad..2f3819c872c 100644 --- a/src/common/Collision/RegularGrid.h +++ b/src/common/Collision/RegularGrid.h @@ -20,7 +20,7 @@ class NodeCreatorFunc = NodeCreator<Node>, /*class BoundsFunc = BoundsTrait<T>,*/ class PositionFunc = PositionTrait<T> > -class RegularGrid2D +class TC_COMMON_API RegularGrid2D { public: @@ -71,7 +71,7 @@ public: } bool contains(const T& value) const { return memberTable.containsKey(&value); } - int size() const { return memberTable.size(); } + int size() const { return uint32(memberTable.size()); } struct Cell { diff --git a/src/common/Common.h b/src/common/Common.h index e8adc55d20d..aa04abacd30 100644 --- a/src/common/Common.h +++ b/src/common/Common.h @@ -21,28 +21,31 @@ #include "Define.h" -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <time.h> -#include <cmath> -#include <errno.h> -#include <signal.h> -#include <assert.h> - -#include <set> -#include <unordered_set> +#include <algorithm> +#include <array> +#include <exception> #include <list> -#include <string> #include <map> -#include <unordered_map> +#include <memory> #include <queue> +#include <set> #include <sstream> -#include <algorithm> -#include <memory> +#include <string> +#include <type_traits> +#include <unordered_map> +#include <unordered_set> #include <vector> -#include <array> +#include <cmath> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <ctime> +#include <cerrno> +#include <csignal> + +#include <boost/optional.hpp> +#include <boost/utility/in_place_factory.hpp> #include <boost/functional/hash.hpp> #include "Debugging/Errors.h" @@ -130,9 +133,9 @@ enum LocaleConstant #define MAX_LOCALES 8 #define MAX_ACCOUNT_TUTORIAL_VALUES 8 -extern char const* localeNames[TOTAL_LOCALES]; +TC_COMMON_API extern char const* localeNames[TOTAL_LOCALES]; -LocaleConstant GetLocaleByName(const std::string& name); +TC_COMMON_API LocaleConstant GetLocaleByName(const std::string& name); typedef std::vector<std::string> StringVector; @@ -151,6 +154,10 @@ typedef std::vector<std::string> StringVector; #define MAX_QUERY_LEN 32*1024 +//! Optional helper class to wrap optional values within. +template <typename T> +using Optional = boost::optional<T>; + namespace Trinity { //! std::make_unique implementation (TODO: remove this once C++14 is supported) diff --git a/src/common/Configuration/BuiltInConfig.cpp b/src/common/Configuration/BuiltInConfig.cpp new file mode 100644 index 00000000000..c2fc3b91766 --- /dev/null +++ b/src/common/Configuration/BuiltInConfig.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "BuiltInConfig.h" +#include "Config.h" +#include "GitRevision.h" + +template<typename Fn> +static std::string GetStringWithDefaultValueFromFunction( + std::string const& key, Fn getter) +{ + std::string const value = sConfigMgr->GetStringDefault(key, ""); + return value.empty() ? getter() : value; +} + +std::string BuiltInConfig::GetCMakeCommand() +{ + return GetStringWithDefaultValueFromFunction( + "CMakeCommand", GitRevision::GetCMakeCommand); +} + +std::string BuiltInConfig::GetBuildDirectory() +{ + return GetStringWithDefaultValueFromFunction( + "BuildDirectory", GitRevision::GetBuildDirectory); +} + +std::string BuiltInConfig::GetSourceDirectory() +{ + return GetStringWithDefaultValueFromFunction( + "SourceDirectory", GitRevision::GetSourceDirectory); +} + +std::string BuiltInConfig::GetMySQLExecutable() +{ + return GetStringWithDefaultValueFromFunction( + "MySQLExecutable", GitRevision::GetMySQLExecutable); +} diff --git a/src/common/Configuration/BuiltInConfig.h b/src/common/Configuration/BuiltInConfig.h new file mode 100644 index 00000000000..0ffa059bc41 --- /dev/null +++ b/src/common/Configuration/BuiltInConfig.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef BUILT_IN_CONFIG_H +#define BUILT_IN_CONFIG_H + +#include <string> +#include "Define.h" + +/// Provides helper functions to access built-in values +/// which can be overwritten in config +namespace BuiltInConfig +{ + /// Returns the CMake command when any is specified in the config, + /// returns the built-in path otherwise + TC_COMMON_API std::string GetCMakeCommand(); + /// Returns the build directory path when any is specified in the config, + /// returns the built-in one otherwise + TC_COMMON_API std::string GetBuildDirectory(); + /// Returns the source directory path when any is specified in the config, + /// returns the built-in one otherwise + TC_COMMON_API std::string GetSourceDirectory(); + /// Returns the path to the mysql executable (`mysql`) when any is specified + /// in the config, returns the built-in one otherwise + TC_COMMON_API std::string GetMySQLExecutable(); + +} // namespace BuiltInConfig + +#endif // BUILT_IN_CONFIG_H diff --git a/src/common/Configuration/Config.cpp b/src/common/Configuration/Config.cpp index 6ac04615315..888aa6ecef3 100644 --- a/src/common/Configuration/Config.cpp +++ b/src/common/Configuration/Config.cpp @@ -21,14 +21,17 @@ #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> #include "Config.h" +#include "Log.h" using namespace boost::property_tree; -bool ConfigMgr::LoadInitial(std::string const& file, std::string& error) +bool ConfigMgr::LoadInitial(std::string const& file, std::vector<std::string> args, + std::string& error) { std::lock_guard<std::mutex> lock(_configLock); _filename = file; + _args = args; try { @@ -56,42 +59,81 @@ bool ConfigMgr::LoadInitial(std::string const& file, std::string& error) return true; } -bool ConfigMgr::Reload(std::string& error) +ConfigMgr* ConfigMgr::instance() { - return LoadInitial(_filename, error); + static ConfigMgr instance; + return &instance; } -std::string ConfigMgr::GetStringDefault(std::string const& name, const std::string& def) +bool ConfigMgr::Reload(std::string& error) { - std::string value = _config.get<std::string>(ptree::path_type(name, '/'), def); + return LoadInitial(_filename, std::move(_args), error); +} - value.erase(std::remove(value.begin(), value.end(), '"'), value.end()); +template<class T> +T ConfigMgr::GetValueDefault(std::string const& name, T def) const +{ + try + { + return _config.get<T>(ptree::path_type(name, '/')); + } + catch (boost::property_tree::ptree_bad_path) + { + 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()); + } + catch (boost::property_tree::ptree_bad_data) + { + 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()); + } - return value; + return def; } -bool ConfigMgr::GetBoolDefault(std::string const& name, bool def) +template<> +std::string ConfigMgr::GetValueDefault<std::string>(std::string const& name, std::string def) const { try { - std::string val = _config.get<std::string>(ptree::path_type(name, '/')); - val.erase(std::remove(val.begin(), val.end(), '"'), val.end()); - return (val == "true" || val == "TRUE" || val == "yes" || val == "YES" || val == "1"); + return _config.get<std::string>(ptree::path_type(name, '/')); + } + catch (boost::property_tree::ptree_bad_path) + { + 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()); } - catch (std::exception const& /*ex*/) + catch (boost::property_tree::ptree_bad_data) { - return def; + 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()); } + + return def; +} + +std::string ConfigMgr::GetStringDefault(std::string const& name, const std::string& def) const +{ + std::string val = GetValueDefault(name, def); + val.erase(std::remove(val.begin(), val.end(), '"'), val.end()); + return val; +} + +bool ConfigMgr::GetBoolDefault(std::string const& name, bool def) const +{ + std::string val = GetValueDefault(name, std::string(def ? "1" : "0")); + val.erase(std::remove(val.begin(), val.end(), '"'), val.end()); + return (val == "1" || val == "true" || val == "TRUE" || val == "yes" || val == "YES"); } -int ConfigMgr::GetIntDefault(std::string const& name, int def) +int ConfigMgr::GetIntDefault(std::string const& name, int def) const { - return _config.get<int>(ptree::path_type(name, '/'), def); + return GetValueDefault(name, def); } -float ConfigMgr::GetFloatDefault(std::string const& name, float def) +float ConfigMgr::GetFloatDefault(std::string const& name, float def) const { - return _config.get<float>(ptree::path_type(name, '/'), def); + return GetValueDefault(name, def); } std::string const& ConfigMgr::GetFilename() diff --git a/src/common/Configuration/Config.h b/src/common/Configuration/Config.h index 5b04212ed7c..573bc7b4a15 100644 --- a/src/common/Configuration/Config.h +++ b/src/common/Configuration/Config.h @@ -19,43 +19,47 @@ #ifndef CONFIG_H #define CONFIG_H +#include "Define.h" + #include <string> #include <list> +#include <vector> #include <mutex> #include <boost/property_tree/ptree.hpp> -class ConfigMgr +class TC_COMMON_API ConfigMgr { - ConfigMgr() { } - ~ConfigMgr() { } + ConfigMgr() = default; + ConfigMgr(ConfigMgr const&) = delete; + ConfigMgr& operator=(ConfigMgr const&) = delete; + ~ConfigMgr() = default; public: /// Method used only for loading main configuration files (authserver.conf and worldserver.conf) - bool LoadInitial(std::string const& file, std::string& error); + bool LoadInitial(std::string const& file, std::vector<std::string> args, + std::string& error); - static ConfigMgr* instance() - { - static ConfigMgr instance; - return &instance; - } + static ConfigMgr* instance(); bool Reload(std::string& error); - std::string GetStringDefault(std::string const& name, const std::string& def); - bool GetBoolDefault(std::string const& name, bool def); - int GetIntDefault(std::string const& name, int def); - float GetFloatDefault(std::string const& name, float def); + std::string GetStringDefault(std::string const& name, const std::string& def) const; + bool GetBoolDefault(std::string const& name, bool def) const; + int GetIntDefault(std::string const& name, int def) const; + float GetFloatDefault(std::string const& name, float def) const; std::string const& GetFilename(); + std::vector<std::string> const& GetArguments() const { return _args; } std::list<std::string> GetKeysByString(std::string const& name); private: std::string _filename; + std::vector<std::string> _args; boost::property_tree::ptree _config; std::mutex _configLock; - ConfigMgr(ConfigMgr const&); - ConfigMgr& operator=(ConfigMgr const&); + template<class T> + T GetValueDefault(std::string const& name, T def) const; }; #define sConfigMgr ConfigMgr::instance() diff --git a/src/common/Cryptography/ARC4.cpp b/src/common/Cryptography/ARC4.cpp index eea523a2090..ead85a18e67 100644 --- a/src/common/Cryptography/ARC4.cpp +++ b/src/common/Cryptography/ARC4.cpp @@ -18,14 +18,14 @@ #include "ARC4.h" -ARC4::ARC4(uint8 len) : m_ctx() +ARC4::ARC4(uint32 len) : m_ctx() { EVP_CIPHER_CTX_init(&m_ctx); EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL); EVP_CIPHER_CTX_set_key_length(&m_ctx, len); } -ARC4::ARC4(uint8 *seed, uint8 len) : m_ctx() +ARC4::ARC4(uint8 *seed, uint32 len) : m_ctx() { EVP_CIPHER_CTX_init(&m_ctx); EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL); diff --git a/src/common/Cryptography/ARC4.h b/src/common/Cryptography/ARC4.h index f39e662e295..df412944ef6 100644 --- a/src/common/Cryptography/ARC4.h +++ b/src/common/Cryptography/ARC4.h @@ -22,11 +22,11 @@ #include <openssl/evp.h> #include "Define.h" -class ARC4 +class TC_COMMON_API ARC4 { public: - ARC4(uint8 len); - ARC4(uint8 *seed, uint8 len); + ARC4(uint32 len); + ARC4(uint8 *seed, uint32 len); ~ARC4(); void Init(uint8 *seed); void UpdateData(int len, uint8 *data); diff --git a/src/common/Cryptography/Authentication/AuthCrypt.h b/src/common/Cryptography/Authentication/AuthCrypt.h index 878391e3ce8..db4de8a7bd1 100644 --- a/src/common/Cryptography/Authentication/AuthCrypt.h +++ b/src/common/Cryptography/Authentication/AuthCrypt.h @@ -23,7 +23,7 @@ class BigNumber; -class AuthCrypt +class TC_COMMON_API AuthCrypt { public: AuthCrypt(); diff --git a/src/common/Cryptography/BigNumber.cpp b/src/common/Cryptography/BigNumber.cpp index 3b85122ebab..0d5dafc336b 100644 --- a/src/common/Cryptography/BigNumber.cpp +++ b/src/common/Cryptography/BigNumber.cpp @@ -163,11 +163,16 @@ uint32 BigNumber::AsDword() return (uint32)BN_get_word(_bn); } -bool BigNumber::isZero() const +bool BigNumber::IsZero() const { return BN_is_zero(_bn); } +bool BigNumber::IsNegative() const +{ + return BN_is_negative(_bn); +} + std::unique_ptr<uint8[]> BigNumber::AsByteArray(int32 minSize, bool littleEndian) { int numBytes = GetNumBytes(); @@ -189,13 +194,19 @@ std::unique_ptr<uint8[]> BigNumber::AsByteArray(int32 minSize, bool littleEndian return ret; } -char * BigNumber::AsHexStr() const +std::string BigNumber::AsHexStr() const { - return BN_bn2hex(_bn); + char* ch = BN_bn2hex(_bn); + std::string ret = ch; + OPENSSL_free(ch); + return ret; } -char * BigNumber::AsDecStr() const +std::string BigNumber::AsDecStr() const { - return BN_bn2dec(_bn); + char* ch = BN_bn2dec(_bn); + std::string ret = ch; + OPENSSL_free(ch); + return ret; } diff --git a/src/common/Cryptography/BigNumber.h b/src/common/Cryptography/BigNumber.h index a5bda50dc72..baf338552d0 100644 --- a/src/common/Cryptography/BigNumber.h +++ b/src/common/Cryptography/BigNumber.h @@ -21,10 +21,11 @@ #include <memory> #include "Define.h" +#include <string> struct bignum_st; -class BigNumber +class TC_COMMON_API BigNumber { public: BigNumber(); @@ -76,7 +77,8 @@ class BigNumber return t %= bn; } - bool isZero() const; + bool IsZero() const; + bool IsNegative() const; BigNumber ModExp(BigNumber const& bn1, BigNumber const& bn2); BigNumber Exp(BigNumber const&); @@ -89,8 +91,8 @@ class BigNumber std::unique_ptr<uint8[]> AsByteArray(int32 minSize = 0, bool littleEndian = true); - char * AsHexStr() const; - char * AsDecStr() const; + std::string AsHexStr() const; + std::string AsDecStr() const; private: struct bignum_st *_bn; diff --git a/src/common/Cryptography/HMACSHA1.h b/src/common/Cryptography/HMACSHA1.h index 29a926d5b16..049847489a6 100644 --- a/src/common/Cryptography/HMACSHA1.h +++ b/src/common/Cryptography/HMACSHA1.h @@ -28,7 +28,7 @@ class BigNumber; #define SEED_KEY_SIZE 16 -class HmacHash +class TC_COMMON_API HmacHash { public: HmacHash(uint32 len, uint8 *seed); diff --git a/src/common/Cryptography/OpenSSLCrypto.h b/src/common/Cryptography/OpenSSLCrypto.h index df1b14b5eda..65155df9af8 100644 --- a/src/common/Cryptography/OpenSSLCrypto.h +++ b/src/common/Cryptography/OpenSSLCrypto.h @@ -18,6 +18,8 @@ #ifndef OPENSSL_CRYPTO_H #define OPENSSL_CRYPTO_H +#include "Define.h" + /** * A group of functions which setup openssl crypto module to work properly in multithreaded enviroment * If not setup properly - it will crash @@ -25,9 +27,9 @@ namespace OpenSSLCrypto { /// Needs to be called before threads using openssl are spawned - void threadsSetup(); + TC_COMMON_API void threadsSetup(); /// Needs to be called after threads using openssl are despawned - void threadsCleanup(); + TC_COMMON_API void threadsCleanup(); } -#endif
\ No newline at end of file +#endif diff --git a/src/common/Cryptography/SHA1.cpp b/src/common/Cryptography/SHA1.cpp index a01bd7844ee..aed4a069827 100644 --- a/src/common/Cryptography/SHA1.cpp +++ b/src/common/Cryptography/SHA1.cpp @@ -18,6 +18,7 @@ #include "SHA1.h" #include "BigNumber.h" +#include "Util.h" #include <cstring> #include <stdarg.h> @@ -67,3 +68,10 @@ void SHA1Hash::Finalize(void) SHA1_Final(mDigest, &mC); } +std::string CalculateSHA1Hash(std::string const& content) +{ + unsigned char digest[SHA_DIGEST_LENGTH]; + SHA1((unsigned char*)content.c_str(), content.length(), (unsigned char*)&digest); + + return ByteArrayToHexStr(digest, SHA_DIGEST_LENGTH); +} diff --git a/src/common/Cryptography/SHA1.h b/src/common/Cryptography/SHA1.h index ffa02176a2d..37ac2cc0166 100644 --- a/src/common/Cryptography/SHA1.h +++ b/src/common/Cryptography/SHA1.h @@ -25,7 +25,7 @@ class BigNumber; -class SHA1Hash +class TC_COMMON_API SHA1Hash { public: SHA1Hash(); @@ -46,5 +46,8 @@ class SHA1Hash SHA_CTX mC; uint8 mDigest[SHA_DIGEST_LENGTH]; }; -#endif +/// Returns the SHA1 hash of the given content as hex string. +TC_COMMON_API std::string CalculateSHA1Hash(std::string const& content); + +#endif diff --git a/src/common/Debugging/Errors.cpp b/src/common/Debugging/Errors.cpp index 1ec66ff6d59..2ce00229e53 100644 --- a/src/common/Debugging/Errors.cpp +++ b/src/common/Debugging/Errors.cpp @@ -96,4 +96,11 @@ void Abort(char const* file, int line, char const* function) exit(1); } +void AbortHandler(int /*sigval*/) +{ + // nothing useful to log here, no way to pass args + *((volatile int*)NULL) = 0; + exit(1); +} + } // namespace Trinity diff --git a/src/common/Debugging/Errors.h b/src/common/Debugging/Errors.h index 38e311a6b13..e4b3563ca96 100644 --- a/src/common/Debugging/Errors.h +++ b/src/common/Debugging/Errors.h @@ -23,16 +23,18 @@ namespace Trinity { - DECLSPEC_NORETURN void Assert(char const* file, int line, char const* function, char const* message) ATTR_NORETURN; - DECLSPEC_NORETURN void Assert(char const* file, int line, char const* function, char const* message, char const* format, ...) ATTR_NORETURN ATTR_PRINTF(5, 6); + DECLSPEC_NORETURN TC_COMMON_API void Assert(char const* file, int line, char const* function, char const* message) ATTR_NORETURN; + DECLSPEC_NORETURN TC_COMMON_API void Assert(char const* file, int line, char const* function, char const* message, char const* format, ...) ATTR_NORETURN ATTR_PRINTF(5, 6); - DECLSPEC_NORETURN void Fatal(char const* file, int line, char const* function, char const* message, ...) ATTR_NORETURN ATTR_PRINTF(4, 5); + DECLSPEC_NORETURN TC_COMMON_API void Fatal(char const* file, int line, char const* function, char const* message, ...) ATTR_NORETURN ATTR_PRINTF(4, 5); - DECLSPEC_NORETURN void Error(char const* file, int line, char const* function, char const* message) ATTR_NORETURN; + DECLSPEC_NORETURN TC_COMMON_API void Error(char const* file, int line, char const* function, char const* message) ATTR_NORETURN; - DECLSPEC_NORETURN void Abort(char const* file, int line, char const* function) ATTR_NORETURN; + DECLSPEC_NORETURN TC_COMMON_API void Abort(char const* file, int line, char const* function) ATTR_NORETURN; - void Warning(char const* file, int line, char const* function, char const* message); + TC_COMMON_API void Warning(char const* file, int line, char const* function, char const* message); + + DECLSPEC_NORETURN TC_COMMON_API void AbortHandler(int sigval) ATTR_NORETURN; } // namespace Trinity diff --git a/src/common/Debugging/WheatyExceptionReport.cpp b/src/common/Debugging/WheatyExceptionReport.cpp index 5b9a1b1bd6c..72abec161b9 100644 --- a/src/common/Debugging/WheatyExceptionReport.cpp +++ b/src/common/Debugging/WheatyExceptionReport.cpp @@ -901,7 +901,7 @@ unsigned /*cbBuffer*/) // will return true. bool bHandled; pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, pSym->ModBase, pSym->TypeIndex, - 0, pVariable, bHandled, pSym->Name, "", false, true); + pVariable, bHandled, pSym->Name, "", false, true); if (!bHandled) { @@ -934,7 +934,6 @@ char * WheatyExceptionReport::DumpTypeIndex( char * pszCurrBuffer, DWORD64 modBase, DWORD dwTypeIndex, -unsigned nestingLevel, DWORD_PTR offset, bool & bHandled, const char* Name, @@ -1022,14 +1021,14 @@ bool logChildren) FormatOutputValue(buffer, btVoid, sizeof(PVOID), (PVOID)offset, sizeof(buffer)); symbolDetails.top().Value = buffer; - if (nestingLevel >= WER_MAX_NESTING_LEVEL) + if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) logChildren = false; // no need to log any children since the address is invalid anyway if (address == NULL || address == DWORD_PTR(-1)) logChildren = false; - pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, nestingLevel + 1, + pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, address, bHandled, Name, addressStr, false, logChildren); if (!bHandled) @@ -1074,19 +1073,19 @@ bool logChildren) switch (innerTypeTag) { case SymTagUDT: - if (nestingLevel >= WER_MAX_NESTING_LEVEL) + if (symbolDetails.size() >= WER_MAX_NESTING_LEVEL) logChildren = false; - pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, nestingLevel + 1, + pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); break; case SymTagPointerType: if (Name != NULL && Name[0] != '\0') symbolDetails.top().Name = Name; - pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, nestingLevel + 1, + pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); break; case SymTagArrayType: - pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, nestingLevel + 1, + pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, offset, bHandled, symbolDetails.top().Name.c_str(), "", false, logChildren); break; default: @@ -1100,7 +1099,7 @@ bool logChildren) symbolDetails.top().HasChildren = true; BasicType basicType = btNoType; - pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, nestingLevel + 1, + pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, innerTypeID, offset, bHandled, Name, "", false, false); // Set Value back to an empty string since the Array object itself has no value, only its elements have @@ -1222,7 +1221,7 @@ bool logChildren) DWORD_PTR dwFinalOffset = offset + dwMemberOffset; pszCurrBuffer = DumpTypeIndex(pszCurrBuffer, modBase, - children.ChildId[i], nestingLevel+1, + children.ChildId[i], dwFinalOffset, bHandled2, ""/*Name */, "", true, true); // If the child wasn't a UDT, format it appropriately diff --git a/src/common/Debugging/WheatyExceptionReport.h b/src/common/Debugging/WheatyExceptionReport.h index eb62d8bceef..34919b19e01 100644 --- a/src/common/Debugging/WheatyExceptionReport.h +++ b/src/common/Debugging/WheatyExceptionReport.h @@ -13,7 +13,7 @@ #define countof _countof #define WER_MAX_ARRAY_ELEMENTS_COUNT 10 -#define WER_MAX_NESTING_LEVEL 5 +#define WER_MAX_NESTING_LEVEL 4 #define WER_LARGE_BUFFER_SIZE 1024 * 128 enum BasicType // Stolen from CVCONST.H in the DIA 2.0 SDK @@ -173,7 +173,7 @@ class WheatyExceptionReport static bool FormatSymbolValue(PSYMBOL_INFO, STACKFRAME64 *, char * pszBuffer, unsigned cbBuffer); - static char * DumpTypeIndex(char *, DWORD64, DWORD, unsigned, DWORD_PTR, bool &, const char*, char*, bool, bool); + static char * DumpTypeIndex(char *, DWORD64, DWORD, DWORD_PTR, bool &, const char*, char*, bool, bool); static void FormatOutputValue(char * pszCurrBuffer, BasicType basicType, DWORD64 length, PVOID pAddress, size_t bufferSize, size_t countOverride = 0); diff --git a/src/common/Define.h b/src/common/Define.h index b34edb6a549..d03d26ad780 100644 --- a/src/common/Define.h +++ b/src/common/Define.h @@ -95,6 +95,45 @@ #endif #endif //COMPILER == COMPILER_GNU +#ifdef TRINITY_API_USE_DYNAMIC_LINKING +# if COMPILER == COMPILER_MICROSOFT +# define TC_API_EXPORT __declspec(dllexport) +# define TC_API_IMPORT __declspec(dllimport) +# elif COMPILER == COMPILER_GNU +# define TC_API_EXPORT __attribute__((visibility("default"))) +# define TC_API_IMPORT +# else +# error compiler not supported! +# endif +#else +# define TC_API_EXPORT +# define TC_API_IMPORT +#endif + +#ifdef TRINITY_API_EXPORT_COMMON +# define TC_COMMON_API TC_API_EXPORT +#else +# define TC_COMMON_API TC_API_IMPORT +#endif + +#ifdef TRINITY_API_EXPORT_DATABASE +# define TC_DATABASE_API TC_API_EXPORT +#else +# define TC_DATABASE_API TC_API_IMPORT +#endif + +#ifdef TRINITY_API_EXPORT_SHARED +# define TC_SHARED_API TC_API_EXPORT +#else +# define TC_SHARED_API TC_API_IMPORT +#endif + +#ifdef TRINITY_API_EXPORT_GAME +# define TC_GAME_API TC_API_EXPORT +#else +# define TC_GAME_API TC_API_IMPORT +#endif + #define UI64FMTD "%" PRIu64 #define UI64LIT(N) UINT64_C(N) diff --git a/src/common/GitRevision.cpp b/src/common/GitRevision.cpp index d0719c09959..702cd01d84b 100644 --- a/src/common/GitRevision.cpp +++ b/src/common/GitRevision.cpp @@ -1,5 +1,4 @@ #include "GitRevision.h" -#include "CompilerDefs.h" #include "revision_data.h" char const* GitRevision::GetHash() @@ -17,6 +16,16 @@ char const* GitRevision::GetBranch() return _BRANCH; } +char const* GitRevision::GetCMakeCommand() +{ + return _CMAKE_COMMAND; +} + +char const* GitRevision::GetBuildDirectory() +{ + return _BUILD_DIRECTORY; +} + char const* GitRevision::GetSourceDirectory() { return _SOURCE_DIRECTORY; @@ -32,19 +41,30 @@ char const* GitRevision::GetFullDatabase() return _FULL_DATABASE; } -#define _PACKAGENAME "TrinityCore" - -char const* GitRevision::GetFullVersion() -{ #if PLATFORM == PLATFORM_WINDOWS -# ifdef _WIN64 - return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win64, " _BUILD_DIRECTIVE ")"; -# else - return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win32, " _BUILD_DIRECTIVE ")"; -# endif +# ifdef _WIN64 +# define TRINITY_PLATFORM_STR "Win64" +# else +# define TRINITY_PLATFORM_STR "Win32" +# endif +#elif PLATFORM == PLATFORM_APPLE +# define TRINITY_PLATFORM_STR "MacOSX" +#elif PLATFORM == PLATFORM_INTEL +# define TRINITY_PLATFORM_STR "Intel" +#else // PLATFORM_UNIX +# define TRINITY_PLATFORM_STR "Unix" +#endif + +#ifndef TRINITY_API_USE_DYNAMIC_LINKING +# define TRINITY_LINKAGE_TYPE_STR "Static" #else - return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Unix, " _BUILD_DIRECTIVE ")"; +# define TRINITY_LINKAGE_TYPE_STR "Dynamic" #endif + +char const* GitRevision::GetFullVersion() +{ + return "TrinityCore rev. " VER_PRODUCTVERSION_STR + " (" TRINITY_PLATFORM_STR ", " _BUILD_DIRECTIVE ", " TRINITY_LINKAGE_TYPE_STR ")"; } char const* GitRevision::GetCompanyNameStr() @@ -66,13 +86,3 @@ char const* GitRevision::GetProductVersionStr() { return VER_PRODUCTVERSION_STR; } - -char const* GitRevision::GetCompilerCFlags() -{ - return COMPILER_C_FLAGS; -} - -char const* GitRevision::GetCompilerCXXFlags() -{ - return COMPILER_CXX_FLAGS; -} diff --git a/src/common/GitRevision.h b/src/common/GitRevision.h index 8d2764ba861..aace8ad2076 100644 --- a/src/common/GitRevision.h +++ b/src/common/GitRevision.h @@ -19,22 +19,23 @@ #define __GITREVISION_H__ #include <string> +#include "Define.h" namespace GitRevision { - char const* GetHash(); - char const* GetDate(); - char const* GetBranch(); - char const* GetSourceDirectory(); - char const* GetMySQLExecutable(); - char const* GetFullDatabase(); - char const* GetFullVersion(); - char const* GetCompanyNameStr(); - char const* GetLegalCopyrightStr(); - char const* GetFileVersionStr(); - char const* GetProductVersionStr(); - char const* GetCompilerCFlags(); - char const* GetCompilerCXXFlags(); + TC_COMMON_API char const* GetHash(); + TC_COMMON_API char const* GetDate(); + TC_COMMON_API char const* GetBranch(); + TC_COMMON_API char const* GetCMakeCommand(); + TC_COMMON_API char const* GetBuildDirectory(); + TC_COMMON_API char const* GetSourceDirectory(); + TC_COMMON_API char const* GetMySQLExecutable(); + TC_COMMON_API char const* GetFullDatabase(); + TC_COMMON_API char const* GetFullVersion(); + TC_COMMON_API char const* GetCompanyNameStr(); + TC_COMMON_API char const* GetLegalCopyrightStr(); + TC_COMMON_API char const* GetFileVersionStr(); + TC_COMMON_API char const* GetProductVersionStr(); } #endif diff --git a/src/common/Logging/Appender.h b/src/common/Logging/Appender.h index f0bfe423a66..d24daa2b60d 100644 --- a/src/common/Logging/Appender.h +++ b/src/common/Logging/Appender.h @@ -41,7 +41,7 @@ enum LogLevel const uint8 MaxLogLevels = 6; -enum AppenderType +enum AppenderType : uint8 { APPENDER_NONE, APPENDER_CONSOLE, @@ -59,7 +59,7 @@ enum AppenderFlags APPENDER_FLAGS_MAKE_FILE_BACKUP = 0x10 // only used by FileAppender }; -struct LogMessage +struct TC_COMMON_API LogMessage { LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) : level(_level), type(_type), text(std::forward<std::string>(_text)), mtime(time(NULL)) @@ -85,7 +85,7 @@ struct LogMessage } }; -class Appender +class TC_COMMON_API Appender { public: Appender(uint8 _id, std::string const& name, LogLevel level = LOG_LEVEL_DISABLED, AppenderFlags flags = APPENDER_FLAGS_NONE); @@ -123,7 +123,7 @@ Appender* CreateAppender(uint8 id, std::string const& name, LogLevel level, Appe return new AppenderImpl(id, name, level, flags, std::forward<ExtraAppenderArgs>(extraArgs)); } -class InvalidAppenderArgsException : public std::length_error +class TC_COMMON_API InvalidAppenderArgsException : public std::length_error { public: explicit InvalidAppenderArgsException(std::string const& message) : std::length_error(message) { } diff --git a/src/common/Logging/AppenderConsole.h b/src/common/Logging/AppenderConsole.h index 5d7eae36b40..96d17207158 100644 --- a/src/common/Logging/AppenderConsole.h +++ b/src/common/Logging/AppenderConsole.h @@ -42,7 +42,7 @@ enum ColorTypes const uint8 MaxColors = uint8(WHITE) + 1; -class AppenderConsole : public Appender +class TC_COMMON_API AppenderConsole : public Appender { public: typedef std::integral_constant<AppenderType, APPENDER_CONSOLE>::type TypeIndex; diff --git a/src/common/Logging/AppenderFile.h b/src/common/Logging/AppenderFile.h index 9ba5d59259c..956b7a70b93 100644 --- a/src/common/Logging/AppenderFile.h +++ b/src/common/Logging/AppenderFile.h @@ -21,7 +21,7 @@ #include <atomic> #include "Appender.h" -class AppenderFile : public Appender +class TC_COMMON_API AppenderFile : public Appender { public: typedef std::integral_constant<AppenderType, APPENDER_FILE>::type TypeIndex; diff --git a/src/common/Logging/Log.cpp b/src/common/Logging/Log.cpp index 4bd0487343d..f7a84fb8b47 100644 --- a/src/common/Logging/Log.cpp +++ b/src/common/Logging/Log.cpp @@ -214,13 +214,13 @@ void Log::ReadLoggersFromConfig() AppenderConsole* appender = new AppenderConsole(NextAppenderId(), "Console", LOG_LEVEL_DEBUG, APPENDER_FLAGS_NONE, ExtraAppenderArgs()); appenders[appender->getId()] = appender; - Logger& logger = loggers[LOGGER_ROOT]; - logger.Create(LOGGER_ROOT, LOG_LEVEL_ERROR); - logger.addAppender(appender->getId(), appender); + Logger& rootLogger = loggers[LOGGER_ROOT]; + rootLogger.Create(LOGGER_ROOT, LOG_LEVEL_ERROR); + rootLogger.addAppender(appender->getId(), appender); - logger = loggers["server"]; - logger.Create("server", LOG_LEVEL_ERROR); - logger.addAppender(appender->getId(), appender); + Logger& serverLogger = loggers["server"]; + serverLogger.Create("server", LOG_LEVEL_INFO); + serverLogger.addAppender(appender->getId(), appender); } } @@ -320,6 +320,12 @@ void Log::Close() appenders.clear(); } +Log* Log::instance() +{ + static Log instance; + return &instance; +} + void Log::Initialize(boost::asio::io_service* ioService) { if (ioService) @@ -331,6 +337,13 @@ void Log::Initialize(boost::asio::io_service* ioService) LoadFromConfig(); } +void Log::SetSynchronous() +{ + delete _strand; + _strand = nullptr; + _ioService = nullptr; +} + void Log::LoadFromConfig() { Close(); diff --git a/src/common/Logging/Log.h b/src/common/Logging/Log.h index a90481ad5d2..6460e404c90 100644 --- a/src/common/Logging/Log.h +++ b/src/common/Logging/Log.h @@ -34,7 +34,7 @@ #define LOGGER_ROOT "root" -class Log +class TC_COMMON_API Log { typedef std::unordered_map<std::string, Logger> LoggerMap; @@ -44,13 +44,10 @@ class Log public: - static Log* instance() - { - static Log instance; - return &instance; - } + static Log* instance(); void Initialize(boost::asio::io_service* ioService); + void SetSynchronous(); // Not threadsafe - should only be called from main() after all threads are joined void LoadFromConfig(); void Close(); bool ShouldLog(std::string const& type, LogLevel level) const; diff --git a/src/common/Logging/LogOperation.h b/src/common/Logging/LogOperation.h index 618629b5423..56e2307d492 100644 --- a/src/common/Logging/LogOperation.h +++ b/src/common/Logging/LogOperation.h @@ -19,11 +19,12 @@ #define LOGOPERATION_H #include <memory> +#include "Define.h" class Logger; struct LogMessage; -class LogOperation +class TC_COMMON_API LogOperation { public: LogOperation(Logger const* _logger, std::unique_ptr<LogMessage>&& _msg) diff --git a/src/common/Logging/Logger.h b/src/common/Logging/Logger.h index 67eab4295a4..4ac2e4494cc 100644 --- a/src/common/Logging/Logger.h +++ b/src/common/Logging/Logger.h @@ -20,7 +20,7 @@ #include "Appender.h" -class Logger +class TC_COMMON_API Logger { public: Logger(); diff --git a/src/common/Metric/Metric.cpp b/src/common/Metric/Metric.cpp new file mode 100644 index 00000000000..9484cebcc72 --- /dev/null +++ b/src/common/Metric/Metric.cpp @@ -0,0 +1,235 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "Metric.h" +#include "Log.h" +#include "Config.h" +#include "Util.h" + +void Metric::Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function<void()> overallStatusLogger) +{ + _realmName = realmName; + _batchTimer = Trinity::make_unique<boost::asio::deadline_timer>(ioService); + _overallStatusTimer = Trinity::make_unique<boost::asio::deadline_timer>(ioService); + _overallStatusLogger = overallStatusLogger; + LoadFromConfigs(); +} + +bool Metric::Connect() +{ + _dataStream.connect(_hostname, _port); + auto error = _dataStream.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()); + _enabled = false; + return false; + } + _dataStream.clear(); + return true; +} + +void Metric::LoadFromConfigs() +{ + bool previousValue = _enabled; + _enabled = sConfigMgr->GetBoolDefault("Metric.Enable", false); + _updateInterval = sConfigMgr->GetIntDefault("Metric.Interval", 10); + if (_updateInterval < 1) + { + TC_LOG_ERROR("metric", "'Metric.Interval' config set to %d, 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); + _overallStatusTimerInterval = 1; + } + + // Schedule a send at this point only if the config changed from Disabled to Enabled. + // Cancel any scheduled operation if the config changed from Enabled to Disabled. + if (_enabled && !previousValue) + { + std::string connectionInfo = sConfigMgr->GetStringDefault("Metric.ConnectionInfo", ""); + if (connectionInfo.empty()) + { + TC_LOG_ERROR("metric", "'Metric.ConnectionInfo' not specified in configuration file."); + return; + } + + Tokenizer tokens(connectionInfo, ';'); + if (tokens.size() != 3) + { + TC_LOG_ERROR("metric", "'Metric.ConnectionInfo' specified with wrong format in configuration file."); + return; + } + + _hostname.assign(tokens[0]); + _port.assign(tokens[1]); + _databaseName.assign(tokens[2]); + Connect(); + + ScheduleSend(); + ScheduleOverallStatusLog(); + } +} + +void Metric::Update() +{ + if (_overallStatusTimerTriggered) + { + _overallStatusTimerTriggered = false; + _overallStatusLogger(); + } +} + +void Metric::LogEvent(std::string const& category, std::string const& title, std::string const& description) +{ + using namespace std::chrono; + + MetricData* data = new MetricData; + data->Category = category; + data->Timestamp = system_clock::now(); + data->Type = METRIC_DATA_EVENT; + data->Title = title; + data->Text = description; + + _queuedData.Enqueue(data); +} + +void Metric::SendBatch() +{ + using namespace std::chrono; + + std::stringstream batchedData; + MetricData* data; + bool firstLoop = true; + while (_queuedData.Dequeue(data)) + { + if (!firstLoop) + batchedData << "\n"; + + batchedData << data->Category; + if (!_realmName.empty()) + batchedData << ",realm=" << _realmName; + + batchedData << " "; + + switch (data->Type) + { + case METRIC_DATA_VALUE: + batchedData << "value=" << data->Value; + break; + case METRIC_DATA_EVENT: + batchedData << "title=\"" << data->Title << "\",text=\"" << data->Text << "\""; + break; + } + + batchedData << " "; + + batchedData << std::to_string(duration_cast<nanoseconds>(data->Timestamp.time_since_epoch()).count()); + + firstLoop = false; + delete data; + } + + // Check if there's any data to send + if (batchedData.tellp() == std::streampos(0)) + { + ScheduleSend(); + return; + } + + if (!_dataStream.good() && !Connect()) + return; + + _dataStream << "POST " << "/write?db=" << _databaseName << " HTTP/1.1\r\n"; + _dataStream << "Host: " << _hostname << ":" << _port << "\r\n"; + _dataStream << "Accept: */*\r\n"; + _dataStream << "Content-Type: application/octet-stream\r\n"; + _dataStream << "Content-Transfer-Encoding: binary\r\n"; + + _dataStream << "Content-Length: " << std::to_string(batchedData.tellp()) << "\r\n\r\n"; + _dataStream << batchedData.rdbuf(); + + std::string http_version; + _dataStream >> http_version; + unsigned int status_code = 0; + _dataStream >> status_code; + if (status_code != 204) + { + TC_LOG_ERROR("metric", "Error sending data, returned HTTP code: %u", status_code); + } + + // Read and ignore the status description + std::string status_description; + std::getline(_dataStream, status_description); + // Read headers + std::string header; + while (std::getline(_dataStream, header) && header != "\r") + { + if (header == "Connection: close\r") + _dataStream.close(); + } + + ScheduleSend(); +} + +void Metric::ScheduleSend() +{ + if (_enabled) + { + _batchTimer->expires_from_now(boost::posix_time::seconds(_updateInterval)); + _batchTimer->async_wait(std::bind(&Metric::SendBatch, this)); + } + else + { + _dataStream.close(); + MetricData* data; + // Clear the queue + while (_queuedData.Dequeue(data)) + ; + } +} + +void Metric::ForceSend() +{ + // Send what's queued only if io_service is stopped (so only on shutdown) + if (_enabled && _batchTimer->get_io_service().stopped()) + SendBatch(); +} + +void Metric::ScheduleOverallStatusLog() +{ + if (_enabled) + { + _overallStatusTimer->expires_from_now(boost::posix_time::seconds(_overallStatusTimerInterval)); + _overallStatusTimer->async_wait([this](const boost::system::error_code&) + { + _overallStatusTimerTriggered = true; + ScheduleOverallStatusLog(); + }); + } +} + +Metric* Metric::instance() +{ + static Metric instance; + return &instance; +} diff --git a/src/common/Metric/Metric.h b/src/common/Metric/Metric.h new file mode 100644 index 00000000000..1855e1d0098 --- /dev/null +++ b/src/common/Metric/Metric.h @@ -0,0 +1,141 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef METRIC_H__ +#define METRIC_H__ + +#include "Common.h" +#include "Threading/MPSCQueue.h" +#include <boost/asio/ip/tcp.hpp> +#include <boost/algorithm/string.hpp> +#include <type_traits> + +enum MetricDataType +{ + METRIC_DATA_VALUE, + METRIC_DATA_EVENT +}; + +struct MetricData +{ + std::string Category; + std::chrono::time_point<std::chrono::system_clock> Timestamp; + MetricDataType Type; + + // LogValue-specific fields + std::string Value; + + // LogEvent-specific fields + std::string Title; + std::string Text; +}; + +class TC_COMMON_API Metric +{ +private: + boost::asio::ip::tcp::iostream _dataStream; + MPSCQueue<MetricData> _queuedData; + std::unique_ptr<boost::asio::deadline_timer> _batchTimer; + std::unique_ptr<boost::asio::deadline_timer> _overallStatusTimer; + int32 _updateInterval = 0; + int32 _overallStatusTimerInterval = 0; + bool _enabled = false; + bool _overallStatusTimerTriggered = false; + std::string _hostname; + std::string _port; + std::string _databaseName; + std::function<void()> _overallStatusLogger; + std::string _realmName; + + bool Connect(); + void SendBatch(); + void ScheduleSend(); + void ScheduleOverallStatusLog(); + + template<class T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr> + static std::string FormatInfluxDBValue(T value) { return std::to_string(value) + 'i'; } + + static std::string FormatInfluxDBValue(std::string const& value) + { + return '"' + boost::replace_all_copy(value, "\"", "\\\"") + '"'; + } + + static std::string FormatInfluxDBValue(bool value) { return value ? "t" : "f"; } + static std::string FormatInfluxDBValue(const char* value) { return FormatInfluxDBValue(std::string(value)); } + static std::string FormatInfluxDBValue(double value) { return std::to_string(value); } + static std::string FormatInfluxDBValue(float value) { return FormatInfluxDBValue(double(value)); } + +public: + static Metric* instance(); + + void Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function<void()> overallStatusLogger = [](){}); + void LoadFromConfigs(); + void Update(); + + template<class T> + void LogValue(std::string const& category, T value) + { + using namespace std::chrono; + + MetricData* data = new MetricData; + data->Category = category; + data->Timestamp = system_clock::now(); + data->Type = METRIC_DATA_VALUE; + data->Value = FormatInfluxDBValue(value); + + _queuedData.Enqueue(data); + } + + void LogEvent(std::string const& category, std::string const& title, std::string const& description); + + void ForceSend(); + bool IsEnabled() const { return _enabled; } +}; + +#define sMetric Metric::instance() + +#if PLATFORM != PLATFORM_WINDOWS +#define TC_METRIC_EVENT(category, title, description) \ + do { \ + if (sMetric->IsEnabled()) \ + sMetric->LogEvent(category, title, description); \ + } while (0) +#define TC_METRIC_VALUE(category, value) \ + do { \ + if (sMetric->IsEnabled()) \ + sMetric->LogValue(category, value); \ + } while (0) +#else +#define TC_METRIC_EVENT(category, title, description) \ + __pragma(warning(push)) \ + __pragma(warning(disable:4127)) \ + do { \ + if (sMetric->IsEnabled()) \ + sMetric->LogEvent(category, title, description); \ + } while (0) \ + __pragma(warning(pop)) +#define TC_METRIC_VALUE(category, value) \ + __pragma(warning(push)) \ + __pragma(warning(disable:4127)) \ + do { \ + if (sMetric->IsEnabled()) \ + sMetric->LogValue(category, value); \ + } while (0) \ + __pragma(warning(pop)) +#endif + +#endif // METRIC_H__ diff --git a/src/server/shared/Service/ServiceWin32.cpp b/src/common/Platform/ServiceWin32.cpp index b6a1682993b..3c34f3e322c 100644 --- a/src/server/shared/Service/ServiceWin32.cpp +++ b/src/common/Platform/ServiceWin32.cpp @@ -261,4 +261,3 @@ bool WinServiceRun() return true; } #endif - diff --git a/src/server/shared/Service/ServiceWin32.h b/src/common/Platform/ServiceWin32.h index 3d67bfe5445..b892ba4e3b6 100644 --- a/src/server/shared/Service/ServiceWin32.h +++ b/src/common/Platform/ServiceWin32.h @@ -26,4 +26,3 @@ bool WinServiceRun(); #endif // _WIN32_SERVICE_ #endif // _WIN32 - diff --git a/src/common/Threading/LockedQueue.h b/src/common/Threading/LockedQueue.h index c6faaaf81ca..21a29d7e53b 100644 --- a/src/common/Threading/LockedQueue.h +++ b/src/common/Threading/LockedQueue.h @@ -57,6 +57,14 @@ public: unlock(); } + //! Adds items back to front of the queue + template<class Iterator> + void readd(Iterator begin, Iterator end) + { + std::lock_guard<std::mutex> lock(_lock); + _queue.insert(_queue.begin(), begin, end); + } + //! Gets the next result in the queue, if any. bool next(T& result) { diff --git a/src/common/Threading/MPSCQueue.h b/src/common/Threading/MPSCQueue.h new file mode 100644 index 00000000000..09648b844be --- /dev/null +++ b/src/common/Threading/MPSCQueue.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef MPSCQueue_h__ +#define MPSCQueue_h__ + +#include <atomic> +#include <utility> + +// C++ implementation of Dmitry Vyukov's lock free MPSC queue +// http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue +template<typename T> +class MPSCQueue +{ +public: + MPSCQueue() : _head(new Node()), _tail(_head.load(std::memory_order_relaxed)) + { + Node* front = _head.load(std::memory_order_relaxed); + front->Next.store(nullptr, std::memory_order_relaxed); + } + + ~MPSCQueue() + { + T* output; + while (this->Dequeue(output)) + ; + + Node* front = _head.load(std::memory_order_relaxed); + delete front; + } + + void Enqueue(T* input) + { + Node* node = new Node(input); + Node* prevHead = _head.exchange(node, std::memory_order_acq_rel); + prevHead->Next.store(node, std::memory_order_release); + } + + bool Dequeue(T*& result) + { + Node* tail = _tail.load(std::memory_order_relaxed); + Node* next = tail->Next.load(std::memory_order_acquire); + if (!next) + return false; + + result = next->Data; + _tail.store(next, std::memory_order_release); + delete tail; + return true; + } + +private: + struct Node + { + Node() = default; + explicit Node(T* data) : Data(data) { Next.store(nullptr, std::memory_order_relaxed); } + + T* Data; + std::atomic<Node*> Next; + }; + + std::atomic<Node*> _head; + std::atomic<Node*> _tail; + + MPSCQueue(MPSCQueue const&) = delete; + MPSCQueue& operator=(MPSCQueue const&) = delete; +}; + +#endif // MPSCQueue_h__ diff --git a/src/common/Utilities/Containers.h b/src/common/Utilities/Containers.h index f3e9432ca4c..5edb245fd87 100644 --- a/src/common/Utilities/Containers.h +++ b/src/common/Utilities/Containers.h @@ -20,6 +20,7 @@ #include "Define.h" #include "Random.h" +#include "Util.h" #include <algorithm> #include <functional> #include <list> @@ -30,9 +31,9 @@ namespace Trinity namespace Containers { template<class T> - void RandomResizeList(std::list<T> &list, uint32 size) + void RandomResizeList(std::list<T>& list, uint32 size) { - size_t list_size = list.size(); + uint32 list_size = uint32(list.size()); while (list_size > size) { @@ -55,7 +56,7 @@ namespace Trinity if (size) RandomResizeList(listCopy, size); - list = listCopy; + list = std::move(listCopy); } /* @@ -67,7 +68,7 @@ namespace Trinity typename C::value_type const& SelectRandomContainerElement(C const& container) { typename C::const_iterator it = container.begin(); - std::advance(it, urand(0, container.size() - 1)); + std::advance(it, urand(0, uint32(container.size()) - 1)); return *it; } @@ -117,6 +118,19 @@ namespace Trinity } /** + * @fn void Trinity::Containers::RandomShuffle(C& container) + * + * @brief Reorder the elements of the container randomly. + * + * @param container Container to reorder + */ + template <class C> + void RandomShuffle(C& container) + { + std::shuffle(container.begin(), container.end(), SFMTEngine::Instance()); + } + + /** * @fn bool Trinity::Containers::Intersects(Iterator first1, Iterator last1, Iterator first2, Iterator last2) * * @brief Checks if two SORTED containers have a common element @@ -156,7 +170,6 @@ namespace Trinity ++itr; } } - } //! namespace Containers } diff --git a/src/common/Utilities/EventMap.h b/src/common/Utilities/EventMap.h index a1aaa9af269..6a314a9e633 100644 --- a/src/common/Utilities/EventMap.h +++ b/src/common/Utilities/EventMap.h @@ -22,7 +22,7 @@ #include "Duration.h" #include "Util.h" -class EventMap +class TC_COMMON_API EventMap { /** * Internal storage type. @@ -122,7 +122,7 @@ public: */ void ScheduleEvent(uint32 eventId, Milliseconds const& time, uint32 group = 0, uint8 phase = 0) { - ScheduleEvent(eventId, time.count(), group, phase); + ScheduleEvent(eventId, uint32(time.count()), group, phase); } /** @@ -145,7 +145,7 @@ public: */ void RescheduleEvent(uint32 eventId, Milliseconds const& time, uint32 group = 0, uint8 phase = 0) { - RescheduleEvent(eventId, time.count(), group, phase); + RescheduleEvent(eventId, uint32(time.count()), group, phase); } /** @@ -169,7 +169,7 @@ public: */ void Repeat(Milliseconds const& time) { - Repeat(time.count()); + Repeat(uint32(time.count())); } /** @@ -190,7 +190,7 @@ public: */ void Repeat(Milliseconds const& minTime, Milliseconds const& maxTime) { - Repeat(minTime.count(), maxTime.count()); + Repeat(uint32(minTime.count()), uint32(maxTime.count())); } /** @@ -218,7 +218,7 @@ public: */ void DelayEvents(Milliseconds const& delay) { - DelayEvents(delay.count()); + DelayEvents(uint32(delay.count())); } /** @@ -239,7 +239,7 @@ public: */ void DelayEvents(Milliseconds const& delay, uint32 group) { - DelayEvents(delay.count(), group); + DelayEvents(uint32(delay.count()), group); } /** diff --git a/src/common/Utilities/EventProcessor.cpp b/src/common/Utilities/EventProcessor.cpp index be74d58b790..2341d0a0872 100644 --- a/src/common/Utilities/EventProcessor.cpp +++ b/src/common/Utilities/EventProcessor.cpp @@ -17,11 +17,20 @@ */ #include "EventProcessor.h" +#include "Errors.h" -EventProcessor::EventProcessor() +void BasicEvent::ScheduleAbort() { - m_time = 0; - m_aborting = false; + ASSERT(IsRunning() + && "Tried to scheduled the abortion of an event twice!"); + m_abortState = AbortState::STATE_ABORT_SCHEDULED; +} + +void BasicEvent::SetAborted() +{ + ASSERT(!IsAborted() + && "Tried to abort an already aborted event!"); + m_abortState = AbortState::STATE_ABORTED; } EventProcessor::~EventProcessor() @@ -39,55 +48,73 @@ void EventProcessor::Update(uint32 p_time) while (((i = m_events.begin()) != m_events.end()) && i->first <= m_time) { // get and remove event from queue - BasicEvent* Event = i->second; + BasicEvent* event = i->second; m_events.erase(i); - if (!Event->to_Abort) + if (event->IsRunning()) { - if (Event->Execute(m_time, p_time)) + if (event->Execute(m_time, p_time)) { // completely destroy event if it is not re-added - delete Event; + delete event; } + continue; } - else + + if (event->IsAbortScheduled()) { - Event->Abort(m_time); - delete Event; + event->Abort(m_time); + // Mark the event as aborted + event->SetAborted(); } + + if (event->IsDeletable()) + { + delete event; + continue; + } + + // Reschedule non deletable events to be checked at + // the next update tick + AddEvent(event, CalculateTime(1), false); } } void EventProcessor::KillAllEvents(bool force) { - // prevent event insertions - m_aborting = true; - - // first, abort all existing events - for (EventList::iterator i = m_events.begin(); i != m_events.end();) + for (auto itr = m_events.begin(); itr != m_events.end();) { - EventList::iterator i_old = i; - ++i; - - i_old->second->to_Abort = true; - i_old->second->Abort(m_time); - if (force || i_old->second->IsDeletable()) + // Abort events which weren't aborted already + if (!itr->second->IsAborted()) { - delete i_old->second; + itr->second->SetAborted(); + itr->second->Abort(m_time); + } - if (!force) // need per-element cleanup - m_events.erase (i_old); + // Skip non-deletable events when we are + // not forcing the event cancellation. + if (!force && !itr->second->IsDeletable()) + { + ++itr; + continue; } + + delete itr->second; + + if (force) + ++itr; // Clear the whole container when forcing + else + itr = m_events.erase(itr); } - // fast clear event list (in force case) if (force) m_events.clear(); } void EventProcessor::AddEvent(BasicEvent* Event, uint64 e_time, bool set_addtime) { - if (set_addtime) Event->m_addTime = m_time; + if (set_addtime) + Event->m_addTime = m_time; Event->m_execTime = e_time; m_events.insert(std::pair<uint64, BasicEvent*>(e_time, Event)); } @@ -96,4 +123,3 @@ uint64 EventProcessor::CalculateTime(uint64 t_offset) const { return(m_time + t_offset); } - diff --git a/src/common/Utilities/EventProcessor.h b/src/common/Utilities/EventProcessor.h index e5eafed79b9..57f3065f323 100644 --- a/src/common/Utilities/EventProcessor.h +++ b/src/common/Utilities/EventProcessor.h @@ -20,20 +20,27 @@ #define __EVENTPROCESSOR_H #include "Define.h" - #include <map> +class EventProcessor; + // Note. All times are in milliseconds here. -class BasicEvent +class TC_COMMON_API BasicEvent { + friend class EventProcessor; + + enum class AbortState : uint8 + { + STATE_RUNNING, + STATE_ABORT_SCHEDULED, + STATE_ABORTED + }; + public: BasicEvent() - { - to_Abort = false; - m_addTime = 0; - m_execTime = 0; - } + : m_abortState(AbortState::STATE_RUNNING), m_addTime(0), m_execTime(0) { } + virtual ~BasicEvent() { } // override destructor to perform some actions on event removal // this method executes when the event is triggered @@ -45,8 +52,16 @@ class BasicEvent virtual void Abort(uint64 /*e_time*/) { } // this method executes when the event is aborted - bool to_Abort; // set by externals when the event is aborted, aborted events don't execute - // and get Abort call when deleted + // Aborts the event at the next update tick + void ScheduleAbort(); + + private: + void SetAborted(); + bool IsRunning() const { return (m_abortState == AbortState::STATE_RUNNING); } + bool IsAbortScheduled() const { return (m_abortState == AbortState::STATE_ABORT_SCHEDULED); } + bool IsAborted() const { return (m_abortState == AbortState::STATE_ABORTED); } + + AbortState m_abortState; // set by externals when the event is aborted, aborted events don't execute // these can be used for time offset control uint64 m_addTime; // time when the event was added to queue, filled by event handler @@ -55,19 +70,20 @@ class BasicEvent typedef std::multimap<uint64, BasicEvent*> EventList; -class EventProcessor +class TC_COMMON_API EventProcessor { public: - EventProcessor(); + EventProcessor() : m_time(0) { } ~EventProcessor(); void Update(uint32 p_time); void KillAllEvents(bool force); void AddEvent(BasicEvent* Event, uint64 e_time, bool set_addtime = true); uint64 CalculateTime(uint64 t_offset) const; + protected: uint64 m_time; EventList m_events; - bool m_aborting; }; + #endif diff --git a/src/server/shared/Networking/MessageBuffer.h b/src/common/Utilities/MessageBuffer.h index 189a56f18b6..d08c4b25bab 100644 --- a/src/server/shared/Networking/MessageBuffer.h +++ b/src/common/Utilities/MessageBuffer.h @@ -20,6 +20,7 @@ #include "Define.h" #include <vector> +#include <cstring> class MessageBuffer { @@ -105,7 +106,7 @@ public: return std::move(_storage); } - MessageBuffer& operator=(MessageBuffer& right) + MessageBuffer& operator=(MessageBuffer const& right) { if (this != &right) { diff --git a/src/common/Utilities/Random.cpp b/src/common/Utilities/Random.cpp index cc013110b01..31318e8f52d 100644 --- a/src/common/Utilities/Random.cpp +++ b/src/common/Utilities/Random.cpp @@ -61,6 +61,14 @@ float frand(float min, float max) return float(GetRng()->Random() * (max - min) + min); } +Milliseconds randtime(Milliseconds const& min, Milliseconds const& max) +{ + long long diff = max.count() - min.count(); + ASSERT(diff >= 0); + ASSERT(diff <= (uint32)-1); + return min + Milliseconds(urand(0, diff)); +} + uint32 rand32() { return GetRng()->BRandom(); diff --git a/src/common/Utilities/Random.h b/src/common/Utilities/Random.h index 5610651a83b..b3ca00219ef 100644 --- a/src/common/Utilities/Random.h +++ b/src/common/Utilities/Random.h @@ -19,29 +19,33 @@ #define Random_h__ #include "Define.h" +#include "Duration.h" #include <limits> #include <random> /* Return a random number in the range min..max. */ -int32 irand(int32 min, int32 max); +TC_COMMON_API int32 irand(int32 min, int32 max); /* Return a random number in the range min..max (inclusive). */ -uint32 urand(uint32 min, uint32 max); +TC_COMMON_API uint32 urand(uint32 min, uint32 max); /* Return a random millisecond value between min and max seconds. Functionally equivalent to urand(min*IN_MILLISECONDS, max*IN_MILLISECONDS). */ -uint32 urandms(uint32 min, uint32 max); +TC_COMMON_API uint32 urandms(uint32 min, uint32 max); /* Return a random number in the range 0 .. UINT32_MAX. */ -uint32 rand32(); +TC_COMMON_API uint32 rand32(); + +/* Return a random time in the range min..max (up to millisecond precision). Only works for values where millisecond difference is a valid uint32. */ +TC_COMMON_API Milliseconds randtime(Milliseconds const& min, Milliseconds const& max); /* Return a random number in the range min..max */ -float frand(float min, float max); +TC_COMMON_API float frand(float min, float max); /* Return a random double from 0.0 to 1.0 (exclusive). */ -double rand_norm(); +TC_COMMON_API double rand_norm(); /* Return a random double from 0.0 to 100.0 (exclusive). */ -double rand_chance(); +TC_COMMON_API double rand_chance(); /* Return true if a random roll fits in the specified chance (range 0-100). */ inline bool roll_chance_f(float chance) @@ -58,7 +62,7 @@ inline bool roll_chance_i(int chance) /* * SFMT wrapper satisfying UniformRandomNumberGenerator concept for use in <random> algorithms */ -class SFMTEngine +class TC_COMMON_API SFMTEngine { public: typedef uint32 result_type; diff --git a/src/common/Utilities/StartProcess.cpp b/src/common/Utilities/StartProcess.cpp new file mode 100644 index 00000000000..f35c6de3b5c --- /dev/null +++ b/src/common/Utilities/StartProcess.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "StartProcess.h" + +#include <atomic> +#include <thread> +#include <functional> + +#include <boost/algorithm/string/join.hpp> +#include <boost/iostreams/stream.hpp> +#include <boost/iostreams/copy.hpp> +#include <boost/iostreams/concepts.hpp> +#include <boost/iostreams/device/file_descriptor.hpp> +#include <boost/process.hpp> +#include <boost/system/system_error.hpp> + +#include "Common.h" +#include "Log.h" + +using namespace boost::process; +using namespace boost::process::initializers; +using namespace boost::iostreams; + +namespace Trinity { + +template<typename T> +class TCLogSink +{ + T callback_; + +public: + typedef char char_type; + typedef sink_tag category; + + // Requires a callback type which has a void(std::string) signature + TCLogSink(T callback) + : callback_(std::move(callback)) { } + + std::streamsize write(const char* str, std::streamsize size) + { + callback_(std::string(str, size)); + return size; + } +}; + +template<typename T> +auto MakeTCLogSink(T&& callback) + -> TCLogSink<typename std::decay<T>::type> +{ + return { std::forward<T>(callback) }; +} + +template<typename T> +static int CreateChildProcess(T waiter, std::string const& executable, + std::vector<std::string> const& args, + std::string const& logger, std::string const& input, + bool secure) +{ + auto outPipe = create_pipe(); + auto errPipe = create_pipe(); + + Optional<file_descriptor_source> inputSource; + + if (!secure) + { + TC_LOG_TRACE(logger, "Starting process \"%s\" with arguments: \"%s\".", + executable.c_str(), boost::algorithm::join(args, " ").c_str()); + } + + // Start the child process + child c = [&] + { + if (!input.empty()) + { + inputSource = file_descriptor_source(input); + + // With binding stdin + return execute(run_exe(boost::filesystem::absolute(executable)), + set_args(args), + inherit_env(), + bind_stdin(*inputSource), + bind_stdout(file_descriptor_sink(outPipe.sink, close_handle)), + bind_stderr(file_descriptor_sink(errPipe.sink, close_handle))); + } + else + { + // Without binding stdin + return execute(run_exe(boost::filesystem::absolute(executable)), + set_args(args), + inherit_env(), + bind_stdout(file_descriptor_sink(outPipe.sink, close_handle)), + bind_stderr(file_descriptor_sink(errPipe.sink, close_handle))); + } + }(); + + file_descriptor_source outFd(outPipe.source, close_handle); + file_descriptor_source errFd(errPipe.source, close_handle); + + auto outInfo = MakeTCLogSink([&](std::string msg) + { + TC_LOG_INFO(logger, "%s", msg.c_str()); + }); + + auto outError = MakeTCLogSink([&](std::string msg) + { + TC_LOG_ERROR(logger, "%s", msg.c_str()); + }); + + copy(outFd, outInfo); + copy(errFd, outError); + + // Call the waiter in the current scope to prevent + // the streams from closing too early on leaving the scope. + int const result = waiter(c); + + if (!secure) + { + TC_LOG_TRACE(logger, ">> Process \"%s\" finished with return value %i.", + executable.c_str(), result); + } + + if (inputSource) + inputSource->close(); + + return result; +} + +int StartProcess(std::string const& executable, std::vector<std::string> const& args, + std::string const& logger, std::string input_file, bool secure) +{ + return CreateChildProcess([](child& c) -> int + { + try + { + return wait_for_exit(c); + } + catch (...) + { + return EXIT_FAILURE; + } + }, executable, args, logger, input_file, secure); +} + +class AsyncProcessResultImplementation + : public AsyncProcessResult +{ + std::string const executable; + std::vector<std::string> const args; + std::string const logger; + std::string const input_file; + bool const is_secure; + + std::atomic<bool> was_terminated; + + // Workaround for missing move support in boost < 1.57 + Optional<std::shared_ptr<std::future<int>>> result; + Optional<std::reference_wrapper<child>> my_child; + +public: + explicit AsyncProcessResultImplementation(std::string executable_, std::vector<std::string> args_, + std::string logger_, std::string input_file_, + bool secure) + : executable(std::move(executable_)), args(std::move(args_)), + logger(std::move(logger_)), input_file(input_file_), + is_secure(secure), was_terminated(false) { } + + AsyncProcessResultImplementation(AsyncProcessResultImplementation const&) = delete; + AsyncProcessResultImplementation& operator= (AsyncProcessResultImplementation const&) = delete; + AsyncProcessResultImplementation(AsyncProcessResultImplementation&&) = delete; + AsyncProcessResultImplementation& operator= (AsyncProcessResultImplementation&&) = delete; + + int StartProcess() + { + ASSERT(!my_child, "Process started already!"); + + return CreateChildProcess([&](child& c) -> int + { + int result; + my_child = std::reference_wrapper<child>(c); + + try + { + result = wait_for_exit(c); + } + catch (...) + { + result = EXIT_FAILURE; + } + + my_child.reset(); + return was_terminated ? EXIT_FAILURE : result; + + }, executable, args, logger, input_file, is_secure); + } + + void SetFuture(std::future<int> result_) + { + result = std::make_shared<std::future<int>>(std::move(result_)); + } + + /// Returns the future which contains the result of the process + /// as soon it is finished. + std::future<int>& GetFutureResult() override + { + ASSERT(*result, "The process wasn't started!"); + return **result; + } + + /// Tries to terminate the process + void Terminate() override + { + if (!my_child) + { + was_terminated = true; + try + { + terminate(my_child->get()); + } + catch(...) + { + // Do nothing + } + } + } +}; + +std::shared_ptr<AsyncProcessResult> + StartAsyncProcess(std::string executable, std::vector<std::string> args, + std::string logger, std::string input_file, bool secure) +{ + auto handle = std::make_shared<AsyncProcessResultImplementation>( + std::move(executable), std::move(args), std::move(logger), std::move(input_file), secure); + + handle->SetFuture(std::async(std::launch::async, [handle] { return handle->StartProcess(); })); + return handle; +} + +Optional<std::string> SearchExecutableInPath(std::string const& filename) +{ + try + { + auto result = search_path(filename); + if (result.empty()) + return boost::none; + else + return result; + } + catch (...) + { + return boost::none; + } +} + +} // namespace Trinity diff --git a/src/common/Utilities/StartProcess.h b/src/common/Utilities/StartProcess.h new file mode 100644 index 00000000000..3b380bd4f4e --- /dev/null +++ b/src/common/Utilities/StartProcess.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef Process_h__ +#define Process_h__ + +#include <future> +#include <memory> +#include "Common.h" + +namespace Trinity { + +/// Starts a process with the given arguments and parameters and will block +/// until the process is finished. +/// When an input path is given, the file will be routed to the processes stdin. +/// When the process is marked as secure no arguments are leaked to logs. +/// Note that most executables expect it's name as the first argument. +TC_COMMON_API int StartProcess(std::string const& executable, std::vector<std::string> const& args, + std::string const& logger, std::string input_file = "", + bool secure = false); + +/// Platform and library independent representation +/// of asynchronous process results +class AsyncProcessResult +{ +public: + virtual ~AsyncProcessResult() { } + + /// Returns the future which contains the result of the process + /// as soon it is finished. + virtual std::future<int>& GetFutureResult() = 0; + + /// Tries to terminate the process + virtual void Terminate() = 0; +}; + +/// Starts a process asynchronously with the given arguments and parameters and +/// returns an AsyncProcessResult immediately which is set, when the process exits. +/// When an input path is given, the file will be routed to the processes stdin. +/// When the process is marked as secure no arguments are leaked to logs. +/// Note that most executables expect it's name as the first argument. +TC_COMMON_API std::shared_ptr<AsyncProcessResult> + StartAsyncProcess(std::string executable, std::vector<std::string> args, + std::string logger, std::string input_file = "", + bool secure = false); + +/// Searches for the given executable in the PATH variable +/// and returns a present optional when it was found. +TC_COMMON_API Optional<std::string> SearchExecutableInPath(std::string const& filename); + +} // namespace Trinity + +#endif // Process_h__ diff --git a/src/common/Utilities/StringFormat.h b/src/common/Utilities/StringFormat.h index d85523bc11f..e21b1024e87 100644 --- a/src/common/Utilities/StringFormat.h +++ b/src/common/Utilities/StringFormat.h @@ -19,7 +19,7 @@ #ifndef TRINITYCORE_STRING_FORMAT_H #define TRINITYCORE_STRING_FORMAT_H -#include "format.h" +#include "cppformat/format.h" namespace Trinity { diff --git a/src/common/Utilities/TaskScheduler.h b/src/common/Utilities/TaskScheduler.h index 8cf5d914128..6784c968683 100644 --- a/src/common/Utilities/TaskScheduler.h +++ b/src/common/Utilities/TaskScheduler.h @@ -46,7 +46,7 @@ class TaskContext; /// with the same duration or a new one. /// It also provides access to the repeat counter which is useful for task that repeat itself often /// but behave different every time (spoken event dialogs for example). -class TaskScheduler +class TC_COMMON_API TaskScheduler { friend class TaskContext; @@ -131,7 +131,7 @@ class TaskScheduler }; }; - class TaskQueue + class TC_COMMON_API TaskQueue { std::multiset<TaskContainer, Compare> container; @@ -401,14 +401,14 @@ private: auto const milli_max = std::chrono::duration_cast<std::chrono::milliseconds>(max); // TC specific: use SFMT URandom - return std::chrono::milliseconds(urand(milli_min.count(), milli_max.count())); + return std::chrono::milliseconds(urand(uint32(milli_min.count()), uint32(milli_max.count()))); } /// Dispatch remaining tasks void Dispatch(success_t const& callback); }; -class TaskContext +class TC_COMMON_API TaskContext { friend class TaskScheduler; diff --git a/src/common/Utilities/Timer.h b/src/common/Utilities/Timer.h index cdce08caaf0..f66bb90c98e 100644 --- a/src/common/Utilities/Timer.h +++ b/src/common/Utilities/Timer.h @@ -25,9 +25,9 @@ inline uint32 getMSTime() { using namespace std::chrono; - static const system_clock::time_point ApplicationStartTime = system_clock::now(); + static const steady_clock::time_point ApplicationStartTime = steady_clock::now(); - return uint32(duration_cast<milliseconds>(system_clock::now() - ApplicationStartTime).count()); + return uint32(duration_cast<milliseconds>(steady_clock::now() - ApplicationStartTime).count()); } inline uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime) diff --git a/src/common/Utilities/Util.cpp b/src/common/Utilities/Util.cpp index 1360253294f..3d8cda66d48 100644 --- a/src/common/Utilities/Util.cpp +++ b/src/common/Utilities/Util.cpp @@ -22,6 +22,7 @@ #include "utf8.h" #include "Errors.h" // for ASSERT #include <stdarg.h> +#include <boost/algorithm/string/case_conv.hpp> #if COMPILER == COMPILER_GNU #include <sys/socket.h> @@ -218,22 +219,29 @@ bool IsIPAddress(char const* ipaddress) } /// create PID file -uint32 CreatePIDFile(const std::string& filename) +uint32 CreatePIDFile(std::string const& filename) { - FILE* pid_file = fopen (filename.c_str(), "w" ); + FILE* pid_file = fopen(filename.c_str(), "w"); if (pid_file == NULL) return 0; + uint32 pid = GetPID(); + + fprintf(pid_file, "%u", pid); + fclose(pid_file); + + return pid; +} + +uint32 GetPID() +{ #ifdef _WIN32 DWORD pid = GetCurrentProcessId(); #else pid_t pid = getpid(); #endif - fprintf(pid_file, "%u", pid ); - fclose(pid_file); - - return (uint32)pid; + return uint32(pid); } size_t utf8length(std::string& utf8str) @@ -418,7 +426,7 @@ bool utf8ToConsole(const std::string& utf8str, std::string& conStr) return false; conStr.resize(wstr.size()); - CharToOemBuffW(&wstr[0], &conStr[0], wstr.size()); + CharToOemBuffW(&wstr[0], &conStr[0], uint32(wstr.size())); #else // not implemented yet conStr = utf8str; @@ -432,7 +440,7 @@ bool consoleToUtf8(const std::string& conStr, std::string& utf8str) #if PLATFORM == PLATFORM_WINDOWS std::wstring wstr; wstr.resize(conStr.size()); - OemToCharBuffW(&conStr[0], &wstr[0], conStr.size()); + OemToCharBuffW(&conStr[0], &wstr[0], uint32(conStr.size())); return WStrToUtf8(wstr, utf8str); #else @@ -450,7 +458,7 @@ bool Utf8FitTo(const std::string& str, std::wstring const& search) return false; // converting to lower case - wstrToLower( temp ); + wstrToLower(temp); if (temp.find(search) == std::wstring::npos) return false; @@ -469,10 +477,10 @@ void utf8printf(FILE* out, const char *str, ...) void vutf8printf(FILE* out, const char *str, va_list* ap) { #if PLATFORM == PLATFORM_WINDOWS - char temp_buf[32*1024]; - wchar_t wtemp_buf[32*1024]; + char temp_buf[32 * 1024]; + wchar_t wtemp_buf[32 * 1024]; - size_t temp_len = vsnprintf(temp_buf, 32*1024, str, *ap); + size_t temp_len = vsnprintf(temp_buf, 32 * 1024, str, *ap); //vsnprintf returns -1 if the buffer is too small if (temp_len == size_t(-1)) temp_len = 32*1024-1; @@ -480,13 +488,24 @@ void vutf8printf(FILE* out, const char *str, va_list* ap) size_t wtemp_len = 32*1024-1; Utf8toWStr(temp_buf, temp_len, wtemp_buf, wtemp_len); - CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], wtemp_len+1); + CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], uint32(wtemp_len + 1)); fprintf(out, "%s", temp_buf); #else vfprintf(out, str, *ap); #endif } +bool Utf8ToUpperOnlyLatin(std::string& utf8String) +{ + std::wstring wstr; + if (!Utf8toWStr(utf8String, wstr)) + return false; + + std::transform(wstr.begin(), wstr.end(), wstr.begin(), wcharToUpperOnlyLatin); + + return WStrToUtf8(wstr, utf8String); +} + std::string ByteArrayToHexStr(uint8 const* bytes, uint32 arrayLen, bool reverse /* = false */) { int32 init = 0; @@ -510,3 +529,34 @@ std::string ByteArrayToHexStr(uint8 const* bytes, uint32 arrayLen, bool reverse return ss.str(); } + +void HexStrToByteArray(std::string const& str, uint8* out, bool reverse /*= false*/) +{ + // string must have even number of characters + if (str.length() & 1) + return; + + int32 init = 0; + int32 end = int32(str.length()); + int8 op = 1; + + if (reverse) + { + init = int32(str.length() - 2); + end = -2; + op = -1; + } + + uint32 j = 0; + for (int32 i = init; i != end; i += 2 * op) + { + char buffer[3] = { str[i], str[i + 1], '\0' }; + out[j++] = uint8(strtoul(buffer, NULL, 16)); + } +} + +bool StringToBool(std::string const& str) +{ + std::string lowerStr = boost::algorithm::to_lower_copy(str); + return lowerStr == "1" || lowerStr == "true" || lowerStr == "yes"; +} diff --git a/src/common/Utilities/Util.h b/src/common/Utilities/Util.h index ab5cabca8d2..cc68f3b2237 100644 --- a/src/common/Utilities/Util.h +++ b/src/common/Utilities/Util.h @@ -40,7 +40,7 @@ template<typename T, class S> struct Finder bool operator()(const std::pair<int, S> &obj) { return obj.second.*idMember_ == val_; } }; -class Tokenizer +class TC_COMMON_API Tokenizer { public: typedef std::vector<char const*> StorageType; @@ -68,15 +68,15 @@ private: StorageType m_storage; }; -void stripLineInvisibleChars(std::string &src); +TC_COMMON_API void stripLineInvisibleChars(std::string &src); -int32 MoneyStringToMoney(const std::string& moneyString); +TC_COMMON_API int32 MoneyStringToMoney(const std::string& moneyString); -struct tm* localtime_r(const time_t* time, struct tm *result); +TC_COMMON_API struct tm* localtime_r(const time_t* time, struct tm *result); -std::string secsToTimeString(uint64 timeInSecs, bool shortText = false, bool hoursOnly = false); -uint32 TimeStringToSecs(const std::string& timestring); -std::string TimeToTimestampStr(time_t t); +TC_COMMON_API std::string secsToTimeString(uint64 timeInSecs, bool shortText = false, bool hoursOnly = false); +TC_COMMON_API uint32 TimeStringToSecs(const std::string& timestring); +TC_COMMON_API std::string TimeToTimestampStr(time_t t); inline void ApplyPercentModFloatVar(float& var, float val, bool apply) { @@ -111,20 +111,20 @@ inline T RoundToInterval(T& num, T floor, T ceil) } // UTF8 handling -bool Utf8toWStr(const std::string& utf8str, std::wstring& wstr); +TC_COMMON_API bool Utf8toWStr(const std::string& utf8str, std::wstring& wstr); // in wsize==max size of buffer, out wsize==real string size -bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize); +TC_COMMON_API bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize); inline bool Utf8toWStr(const std::string& utf8str, wchar_t* wstr, size_t& wsize) { return Utf8toWStr(utf8str.c_str(), utf8str.size(), wstr, wsize); } -bool WStrToUtf8(std::wstring const& wstr, std::string& utf8str); +TC_COMMON_API bool WStrToUtf8(std::wstring const& wstr, std::string& utf8str); // size==real string size -bool WStrToUtf8(wchar_t* wstr, size_t size, std::string& utf8str); +TC_COMMON_API bool WStrToUtf8(wchar_t* wstr, size_t size, std::string& utf8str); -size_t utf8length(std::string& utf8str); // set string to "" if invalid utf8 sequence -void utf8truncate(std::string& utf8str, size_t len); +TC_COMMON_API size_t utf8length(std::string& utf8str); // set string to "" if invalid utf8 sequence +TC_COMMON_API void utf8truncate(std::string& utf8str, size_t len); inline bool isBasicLatinCharacter(wchar_t wchar) { @@ -303,19 +303,24 @@ inline void wstrToLower(std::wstring& str) std::transform( str.begin(), str.end(), str.begin(), wcharToLower ); } -std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension); +TC_COMMON_API std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension); -bool utf8ToConsole(const std::string& utf8str, std::string& conStr); -bool consoleToUtf8(const std::string& conStr, std::string& utf8str); -bool Utf8FitTo(const std::string& str, std::wstring const& search); -void utf8printf(FILE* out, const char *str, ...); -void vutf8printf(FILE* out, const char *str, va_list* ap); +TC_COMMON_API bool utf8ToConsole(const std::string& utf8str, std::string& conStr); +TC_COMMON_API bool consoleToUtf8(const std::string& conStr, std::string& utf8str); +TC_COMMON_API bool Utf8FitTo(const std::string& str, std::wstring const& search); +TC_COMMON_API void utf8printf(FILE* out, const char *str, ...); +TC_COMMON_API void vutf8printf(FILE* out, const char *str, va_list* ap); +TC_COMMON_API bool Utf8ToUpperOnlyLatin(std::string& utf8String); -bool IsIPAddress(char const* ipaddress); +TC_COMMON_API bool IsIPAddress(char const* ipaddress); -uint32 CreatePIDFile(const std::string& filename); +TC_COMMON_API uint32 CreatePIDFile(std::string const& filename); +TC_COMMON_API uint32 GetPID(); -std::string ByteArrayToHexStr(uint8 const* bytes, uint32 length, bool reverse = false); +TC_COMMON_API std::string ByteArrayToHexStr(uint8 const* bytes, uint32 length, bool reverse = false); +TC_COMMON_API void HexStrToByteArray(std::string const& str, uint8* out, bool reverse = false); + +TC_COMMON_API bool StringToBool(std::string const& str); // simple class for not-modifyable list template <typename T> diff --git a/src/genrev/CMakeLists.txt b/src/genrev/CMakeLists.txt index 91a13609037..355e2043b51 100644 --- a/src/genrev/CMakeLists.txt +++ b/src/genrev/CMakeLists.txt @@ -13,3 +13,8 @@ add_custom_target(revision_data.h ALL COMMAND "${CMAKE_COMMAND}" -DBUILDDIR="${CMAKE_BINARY_DIR}" -P "${CMAKE_SOURCE_DIR}/cmake/genrev.cmake" "${CMAKE_BINARY_DIR}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" ) + +set_target_properties(revision_data.h + PROPERTIES + FOLDER + "server") diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index 9a454696ca8..2c7a4773e88 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -12,16 +12,19 @@ # This to stop a few silly crashes that could have been avoided IF people # weren't doing some -O3 psychooptimizations etc. -find_package(MySQL REQUIRED) - if(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW) add_definitions(-fno-delete-null-pointer-checks) endif() -set(sources_windows_Debugging - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h -) +if(WIN32) + set(sources_windows + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h + ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.cpp + ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.h + ) +endif(WIN32) + add_subdirectory(database) add_subdirectory(shared) add_subdirectory(game) diff --git a/src/server/authserver/CMakeLists.txt b/src/server/authserver/CMakeLists.txt index c11deec39bb..d1f0e4460e9 100644 --- a/src/server/authserver/CMakeLists.txt +++ b/src/server/authserver/CMakeLists.txt @@ -10,66 +10,29 @@ ########### authserver ############### -file(GLOB_RECURSE sources_authentication Authentication/*.cpp Authentication/*.h) -file(GLOB_RECURSE sources_realms Realms/*.cpp Realms/*.h) -file(GLOB_RECURSE sources_server Server/*.cpp Server/*.h) -file(GLOB sources_localdir *.cpp *.h) - -if (USE_COREPCH) - set(authserver_PCH_HDR PrecompiledHeaders/authPCH.h) - set(authserver_PCH_SRC PrecompiledHeaders/authPCH.cpp) -endif() - -set(authserver_SRCS - ${authserver_SRCS} - ${sources_authentication} - ${sources_realms} - ${sources_server} - ${sources_localdir} -) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) if( WIN32 ) - set(authserver_SRCS - ${authserver_SRCS} - ${sources_windows_Debugging} - ) + list(APPEND PRIVATE_SOURCES ${sources_windows}) if ( MSVC ) - set(authserver_SRCS - ${authserver_SRCS} - authserver.rc - ) - endif () + list(APPEND PRIVATE_SOURCES authserver.rc) + endif() endif() -include_directories( - ${CMAKE_BINARY_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/Authentication - ${CMAKE_CURRENT_SOURCE_DIR}/Realms - ${CMAKE_CURRENT_SOURCE_DIR}/Server - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/src/common/ - ${CMAKE_SOURCE_DIR}/src/common/Configuration - ${CMAKE_SOURCE_DIR}/src/common/Cryptography - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/database - ${CMAKE_SOURCE_DIR}/src/server/database/Database - ${CMAKE_SOURCE_DIR}/src/server/database/Logging - ${CMAKE_SOURCE_DIR}/src/server/shared/Networking - ${CMAKE_SOURCE_DIR}/src/server/shared/Packets - ${CMAKE_SOURCE_DIR}/src/server/shared/Service - ${MYSQL_INCLUDE_DIR} - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) +if (USE_COREPCH) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/authPCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/authPCH.cpp) +endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) add_executable(authserver - ${authserver_SRCS} - ${authserver_PCH_SRC} + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES} ) if( NOT WIN32 ) @@ -79,15 +42,25 @@ if( NOT WIN32 ) endif() target_link_libraries(authserver - common - shared - format - database - ${MYSQL_LIBRARY} - ${OPENSSL_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ${Boost_LIBRARIES} -) + PUBLIC + shared) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) + +target_include_directories(authserver + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(authserver + PROPERTIES + FOLDER + "server") if( WIN32 ) if ( MSVC ) @@ -113,5 +86,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(authserver ${authserver_PCH_HDR} ${authserver_PCH_SRC}) + add_cxx_pch(authserver ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif() diff --git a/src/server/authserver/Main.cpp b/src/server/authserver/Main.cpp index 0c812ebd494..1392900fb9a 100644 --- a/src/server/authserver/Main.cpp +++ b/src/server/authserver/Main.cpp @@ -36,12 +36,14 @@ #include "GitRevision.h" #include "Util.h" #include <iostream> +#include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> #include <openssl/opensslv.h> #include <openssl/crypto.h> using boost::asio::ip::tcp; using namespace boost::program_options; +namespace fs = boost::filesystem; #ifndef _TRINITY_REALM_CONFIG # define _TRINITY_REALM_CONFIG "authserver.conf" @@ -68,16 +70,20 @@ bool StartDB(); void StopDB(); void SignalHandler(const boost::system::error_code& error, int signalNumber); void KeepDatabaseAliveHandler(const boost::system::error_code& error); -variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile, std::string& configService); +void BanExpiryHandler(boost::system::error_code const& error); +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService); boost::asio::io_service* _ioService; boost::asio::deadline_timer* _dbPingTimer; uint32 _dbPingInterval; -LoginDatabaseWorkerPool LoginDatabase; +boost::asio::deadline_timer* _banExpiryCheckTimer; +uint32 _banExpiryCheckInterval; int main(int argc, char** argv) { - std::string configFile = _TRINITY_REALM_CONFIG; + signal(SIGABRT, &Trinity::AbortHandler); + + auto configFile = fs::absolute(_TRINITY_REALM_CONFIG); std::string configService; auto vm = GetConsoleArguments(argc, argv, configFile, configService); // exit if help or version is enabled @@ -94,7 +100,9 @@ int main(int argc, char** argv) #endif std::string configError; - if (!sConfigMgr->LoadInitial(configFile, configError)) + if (!sConfigMgr->LoadInitial(configFile.generic_string(), + std::vector<std::string>(argv, argv + argc), + configError)) { printf("Error in config file: %s\n", configError.c_str()); return 1; @@ -105,7 +113,7 @@ int main(int argc, char** argv) TC_LOG_INFO("server.authserver", "%s (authserver)", GitRevision::GetFullVersion()); TC_LOG_INFO("server.authserver", "<Ctrl-C> to stop.\n"); - TC_LOG_INFO("server.authserver", "Using configuration file %s.", configFile.c_str()); + TC_LOG_INFO("server.authserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); TC_LOG_INFO("server.authserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); TC_LOG_INFO("server.authserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); @@ -131,7 +139,7 @@ int main(int argc, char** argv) // Get the list of realms for the server sRealmList->Initialize(*_ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20)); - if (sRealmList->size() == 0) + if (sRealmList->GetRealms().empty()) { TC_LOG_ERROR("server.authserver", "No valid realms specified."); StopDB(); @@ -169,6 +177,11 @@ int main(int argc, char** argv) _dbPingTimer->expires_from_now(boost::posix_time::minutes(_dbPingInterval)); _dbPingTimer->async_wait(KeepDatabaseAliveHandler); + _banExpiryCheckInterval = sConfigMgr->GetIntDefault("BanExpiryCheckInterval", 60); + _banExpiryCheckTimer = new boost::asio::deadline_timer(*_ioService); + _banExpiryCheckTimer->expires_from_now(boost::posix_time::seconds(_banExpiryCheckInterval)); + _banExpiryCheckTimer->async_wait(BanExpiryHandler); + #if PLATFORM == PLATFORM_WINDOWS if (m_ServiceStatus != -1) { @@ -181,10 +194,13 @@ int main(int argc, char** argv) // Start the io service worker loop _ioService->run(); + _banExpiryCheckTimer->cancel(); _dbPingTimer->cancel(); sAuthSocketMgr.StopNetwork(); + sRealmList->Close(); + // Close the Database Pool and library StopDB(); @@ -192,6 +208,7 @@ int main(int argc, char** argv) signals.cancel(); + delete _banExpiryCheckTimer; delete _dbPingTimer; delete _ioService; return 0; @@ -242,6 +259,18 @@ void KeepDatabaseAliveHandler(const boost::system::error_code& error) } } +void BanExpiryHandler(boost::system::error_code const& error) +{ + if (!error) + { + LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS)); + LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS)); + + _banExpiryCheckTimer->expires_from_now(boost::posix_time::seconds(_banExpiryCheckInterval)); + _banExpiryCheckTimer->async_wait(BanExpiryHandler); + } +} + #if PLATFORM == PLATFORM_WINDOWS void ServiceStatusWatcher(boost::system::error_code const& error) { @@ -261,13 +290,14 @@ void ServiceStatusWatcher(boost::system::error_code const& error) } #endif -variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile, std::string& configService) +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService) { options_description all("Allowed options"); all.add_options() ("help,h", "print usage message") ("version,v", "print version build info") - ("config,c", value<std::string>(&configFile)->default_value(_TRINITY_REALM_CONFIG), "use <arg> as configuration file") + ("config,c", value<fs::path>(&configFile)->default_value(fs::absolute(_TRINITY_REALM_CONFIG)), + "use <arg> as configuration file") ; #if PLATFORM == PLATFORM_WINDOWS options_description win("Windows platform specific options"); diff --git a/src/server/authserver/Realms/RealmList.h b/src/server/authserver/Realms/RealmList.h deleted file mode 100644 index cc5c88c01f2..00000000000 --- a/src/server/authserver/Realms/RealmList.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#ifndef _REALMLIST_H -#define _REALMLIST_H - -#include <boost/asio/ip/address.hpp> -#include <boost/asio/ip/tcp.hpp> -#include <boost/asio/io_service.hpp> -#include "Common.h" - -using namespace boost::asio; - -enum RealmFlags -{ - REALM_FLAG_NONE = 0x00, - REALM_FLAG_INVALID = 0x01, - REALM_FLAG_OFFLINE = 0x02, - REALM_FLAG_SPECIFYBUILD = 0x04, - REALM_FLAG_UNK1 = 0x08, - REALM_FLAG_UNK2 = 0x10, - REALM_FLAG_RECOMMENDED = 0x20, - REALM_FLAG_NEW = 0x40, - REALM_FLAG_FULL = 0x80 -}; - -// Storage object for a realm -struct Realm -{ - ip::address ExternalAddress; - ip::address LocalAddress; - ip::address LocalSubnetMask; - uint16 port; - std::string name; - uint8 icon; - RealmFlags flag; - uint8 timezone; - uint32 m_ID; - AccountTypes allowedSecurityLevel; - float populationLevel; - uint32 gamebuild; -}; - -/// Storage object for the list of realms on the server -class RealmList -{ -public: - typedef std::map<std::string, Realm> RealmMap; - - static RealmList* instance() - { - static RealmList instance; - return &instance; - } - - ~RealmList(); - - void Initialize(boost::asio::io_service& ioService, uint32 updateInterval); - - void UpdateIfNeed(); - - void AddRealm(const Realm& NewRealm) { m_realms[NewRealm.name] = NewRealm; } - - RealmMap::const_iterator begin() const { return m_realms.begin(); } - RealmMap::const_iterator end() const { return m_realms.end(); } - uint32 size() const { return m_realms.size(); } - -private: - RealmList(); - - void UpdateRealms(bool init = false); - void UpdateRealm(uint32 id, const std::string& name, ip::address const& address, ip::address const& localAddr, - ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population, uint32 build); - - RealmMap m_realms; - uint32 m_UpdateInterval; - time_t m_NextUpdateTime; - boost::asio::ip::tcp::resolver* _resolver; -}; - -#define sRealmList RealmList::instance() -#endif diff --git a/src/server/authserver/Server/AuthSession.cpp b/src/server/authserver/Server/AuthSession.cpp index 60e9b734b13..ec72651ecb7 100644 --- a/src/server/authserver/Server/AuthSession.cpp +++ b/src/server/authserver/Server/AuthSession.cpp @@ -43,12 +43,6 @@ enum eAuthCmd XFER_CANCEL = 0x34 }; -enum eStatus -{ - STATUS_CONNECTED = 0, - STATUS_AUTHED -}; - #pragma pack(push, 1) typedef struct AUTH_LOGON_CHALLENGE_C @@ -115,11 +109,10 @@ enum class BufferSizes : uint32 SRP_6_S = 0x20, }; +#define MAX_ACCEPTED_CHALLENGE_SIZE (sizeof(AUTH_LOGON_CHALLENGE_C) + 16) + #define AUTH_LOGON_CHALLENGE_INITIAL_SIZE 4 #define REALM_LIST_PACKET_SIZE 5 -#define XFER_ACCEPT_SIZE 1 -#define XFER_RESUME_SIZE 9 -#define XFER_CANCEL_SIZE 1 std::unordered_map<uint8, AuthHandler> AuthSession::InitHandlers() { @@ -130,15 +123,103 @@ std::unordered_map<uint8, AuthHandler> AuthSession::InitHandlers() handlers[AUTH_RECONNECT_CHALLENGE] = { STATUS_CONNECTED, AUTH_LOGON_CHALLENGE_INITIAL_SIZE, &AuthSession::HandleReconnectChallenge }; handlers[AUTH_RECONNECT_PROOF] = { STATUS_CONNECTED, sizeof(AUTH_RECONNECT_PROOF_C), &AuthSession::HandleReconnectProof }; handlers[REALM_LIST] = { STATUS_AUTHED, REALM_LIST_PACKET_SIZE, &AuthSession::HandleRealmList }; - handlers[XFER_ACCEPT] = { STATUS_AUTHED, XFER_ACCEPT_SIZE, &AuthSession::HandleXferAccept }; - handlers[XFER_RESUME] = { STATUS_AUTHED, XFER_RESUME_SIZE, &AuthSession::HandleXferResume }; - handlers[XFER_CANCEL] = { STATUS_AUTHED, XFER_CANCEL_SIZE, &AuthSession::HandleXferCancel }; return handlers; } std::unordered_map<uint8, AuthHandler> const Handlers = AuthSession::InitHandlers(); +void AccountInfo::LoadResult(Field* fields) +{ + // 0 1 2 3 4 5 6 + //SELECT a.id, a.username, a.locked, a.lock_country, a.last_ip, a.failed_logins, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, + // 7 8 9 10 11 12 + // ab.unbandate = ab.bandate, aa.gmlevel, a.token_key, a.sha_pass_hash, a.v, a.s + //FROM account a LEFT JOIN account_access aa ON a.id = aa.id LEFT JOIN account_banned ab ON ab.id = a.id AND ab.active = 1 WHERE a.username = ? + + Id = fields[0].GetUInt32(); + Login = fields[1].GetString(); + IsLockedToIP = fields[2].GetBool(); + LockCountry = fields[3].GetString(); + LastIP = fields[4].GetString(); + FailedLogins = fields[5].GetUInt32(); + IsBanned = fields[6].GetUInt64() != 0; + IsPermanenetlyBanned = fields[7].GetUInt64() != 0; + SecurityLevel = AccountTypes(fields[8].GetUInt8()); + + // Use our own uppercasing of the account name instead of using UPPER() in mysql query + // This is how the account was created in the first place and changing it now would result in breaking + // login for all accounts having accented characters in their name + Utf8ToUpperOnlyLatin(Login); +} + +AuthSession::AuthSession(tcp::socket&& socket) : Socket(std::move(socket)), +_sentChallenge(false), _sentProof(false), +_status(STATUS_CONNECTED), _build(0), _expversion(0) +{ + N.SetHexStr("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7"); + g.SetDword(7); +} + +void AuthSession::Start() +{ + std::string ip_address = GetRemoteIpAddress().to_string(); + TC_LOG_TRACE("session", "Accepted connection from %s", ip_address.c_str()); + + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); + stmt->setString(0, ip_address); + stmt->setUInt32(1, inet_addr(ip_address.c_str())); + + _queryCallback = std::bind(&AuthSession::CheckIpCallback, this, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); +} + +bool AuthSession::Update() +{ + if (!AuthSocket::Update()) + return false; + + if (_queryFuture.valid() && _queryFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) + { + auto callback = _queryCallback; + _queryCallback = nullptr; + callback(_queryFuture.get()); + } + + return true; +} + +void AuthSession::CheckIpCallback(PreparedQueryResult result) +{ + if (result) + { + bool banned = false; + do + { + Field* fields = result->Fetch(); + if (fields[0].GetUInt64() != 0) + banned = true; + + if (!fields[1].GetString().empty()) + _ipCountry = fields[1].GetString(); + + } while (result->NextRow()); + + if (banned) + { + ByteBuffer pkt; + pkt << uint8(AUTH_LOGON_CHALLENGE); + pkt << uint8(0x00); + pkt << uint8(WOW_FAIL_BANNED); + SendPacket(pkt); + TC_LOG_DEBUG("session", "[AuthSession::CheckIpCallback] Banned ip '%s:%d' tries to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort()); + return; + } + } + + AsyncRead(); +} + void AuthSession::ReadHandler() { MessageBuffer& packet = GetReadBuffer(); @@ -153,6 +234,12 @@ void AuthSession::ReadHandler() break; } + if (_status != itr->second.status) + { + CloseSocket(); + return; + } + uint16 size = uint16(itr->second.packetSize); if (packet.GetActiveSize() < size) break; @@ -161,12 +248,17 @@ void AuthSession::ReadHandler() { sAuthLogonChallenge_C* challenge = reinterpret_cast<sAuthLogonChallenge_C*>(packet.GetReadPointer()); size += challenge->size; + if (size > MAX_ACCEPTED_CHALLENGE_SIZE) + { + CloseSocket(); + return; + } } if (packet.GetActiveSize() < size) break; - if (!(*this.*Handlers.at(cmd).handler)()) + if (!(*this.*itr->second.handler)()) { CloseSocket(); return; @@ -187,233 +279,209 @@ void AuthSession::SendPacket(ByteBuffer& packet) { MessageBuffer buffer; buffer.Write(packet.contents(), packet.size()); - - std::unique_lock<std::mutex> guard(_writeLock); - - QueuePacket(std::move(buffer), guard); + QueuePacket(std::move(buffer)); } } bool AuthSession::HandleLogonChallenge() { + if (_sentChallenge) + return false; + + _sentChallenge = true; + sAuthLogonChallenge_C* challenge = reinterpret_cast<sAuthLogonChallenge_C*>(GetReadBuffer().GetReadPointer()); + if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) + return false; - //TC_LOG_DEBUG("server.authserver", "[AuthChallenge] got full packet, %#04x bytes", challenge->size); - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] name(%d): '%s'", challenge->I_len, challenge->I); + std::string login((const char*)challenge->I, challenge->I_len); + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] '%s'", login.c_str()); - ByteBuffer pkt; + if (_queryCallback) + { + ByteBuffer pkt; + pkt << uint8(AUTH_LOGON_CHALLENGE); + pkt << uint8(0x00); + pkt << uint8(WOW_FAIL_DB_BUSY); + SendPacket(pkt); + + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] %s attempted to log too quick after previous attempt!", login.c_str()); + return true; + } - _login.assign((const char*)challenge->I, challenge->I_len); _build = challenge->build; _expversion = uint8(AuthHelper::IsPostBCAcceptedClientBuild(_build) ? POST_BC_EXP_FLAG : (AuthHelper::IsPreBCAcceptedClientBuild(_build) ? PRE_BC_EXP_FLAG : NO_VALID_EXP_FLAG)); - _os = (const char*)challenge->os; - - if (_os.size() > 4) - return false; + std::array<char, 5> os; + os.fill('\0'); + memcpy(os.data(), challenge->os, sizeof(challenge->os)); + _os = os.data(); // Restore string order as its byte order is reversed std::reverse(_os.begin(), _os.end()); + _localizationName.resize(4); + for (int i = 0; i < 4; ++i) + _localizationName[i] = challenge->country[4 - i - 1]; + + // Get the account details from the account table + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGONCHALLENGE); + stmt->setString(0, login); + + _queryCallback = std::bind(&AuthSession::LogonChallengeCallback, this, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); + return true; +} + +void AuthSession::LogonChallengeCallback(PreparedQueryResult result) +{ + ByteBuffer pkt; pkt << uint8(AUTH_LOGON_CHALLENGE); pkt << uint8(0x00); - // Verify that this IP is not in the ip_banned table - LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS)); + if (!result) + { + pkt << uint8(WOW_FAIL_UNKNOWN_ACCOUNT); + SendPacket(pkt); + return; + } + + Field* fields = result->Fetch(); + + _accountInfo.LoadResult(fields); std::string ipAddress = GetRemoteIpAddress().to_string(); uint16 port = GetRemotePort(); - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED); - stmt->setString(0, ipAddress); - PreparedQueryResult result = LoginDatabase.Query(stmt); - if (result) + // If the IP is 'locked', check that the player comes indeed from the correct IP address + if (_accountInfo.IsLockedToIP) { - pkt << uint8(WOW_FAIL_BANNED); - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] Banned ip tries to login!", ipAddress.c_str(), port); + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is locked to IP - '%s' is logging in from '%s'", _accountInfo.Login.c_str(), _accountInfo.LastIP.c_str(), ipAddress.c_str()); + if (_accountInfo.LastIP != ipAddress) + { + pkt << uint8(WOW_FAIL_LOCKED_ENFORCED); + SendPacket(pkt); + return; + } } else { - // Get the account details from the account table - // No SQL injection (prepared statement) - stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGONCHALLENGE); - stmt->setString(0, _login); - - PreparedQueryResult res2 = LoginDatabase.Query(stmt); - if (res2) + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is not locked to ip", _accountInfo.Login.c_str()); + if (_accountInfo.LockCountry.empty() || _accountInfo.LockCountry == "00") + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is not locked to country", _accountInfo.Login.c_str()); + else if (!_accountInfo.LockCountry.empty() && !_ipCountry.empty()) { - Field* fields = res2->Fetch(); - - // If the IP is 'locked', check that the player comes indeed from the correct IP address - bool locked = false; - if (fields[2].GetUInt8() == 1) // if ip is locked + TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is locked to country: '%s' Player country is '%s'", _accountInfo.Login.c_str(), _accountInfo.LockCountry.c_str(), _ipCountry.c_str()); + if (_ipCountry != _accountInfo.LockCountry) { - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is locked to IP - '%s'", _login.c_str(), fields[4].GetCString()); - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Player address is '%s'", ipAddress.c_str()); - - if (strcmp(fields[4].GetCString(), ipAddress.c_str()) != 0) - { - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account IP differs"); - pkt << uint8(WOW_FAIL_LOCKED_ENFORCED); - locked = true; - } - else - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account IP matches"); - } - else - { - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is not locked to ip", _login.c_str()); - std::string accountCountry = fields[3].GetString(); - if (accountCountry.empty() || accountCountry == "00") - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is not locked to country", _login.c_str()); - else if (!accountCountry.empty()) - { - uint32 ip = inet_addr(ipAddress.c_str()); - EndianConvertReverse(ip); - - stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGON_COUNTRY); - stmt->setUInt32(0, ip); - if (PreparedQueryResult sessionCountryQuery = LoginDatabase.Query(stmt)) - { - std::string loginCountry = (*sessionCountryQuery)[0].GetString(); - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account '%s' is locked to country: '%s' Player country is '%s'", _login.c_str(), - accountCountry.c_str(), loginCountry.c_str()); - - if (loginCountry != accountCountry) - { - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account country differs."); - pkt << uint8(WOW_FAIL_UNLOCKABLE_LOCK); - locked = true; - } - else - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] Account country matches"); - } - else - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] IP2NATION Table empty"); - } + pkt << uint8(WOW_FAIL_UNLOCKABLE_LOCK); + SendPacket(pkt); + return; } + } + } - if (!locked) - { - //set expired bans to inactive - LoginDatabase.DirectExecute(LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS)); - - // If the account is banned, reject the logon attempt - stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); - stmt->setUInt32(0, fields[1].GetUInt32()); - PreparedQueryResult banresult = LoginDatabase.Query(stmt); - if (banresult) - { - if ((*banresult)[0].GetUInt32() == (*banresult)[1].GetUInt32()) - { - pkt << uint8(WOW_FAIL_BANNED); - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] Banned account %s tried to login!", ipAddress.c_str(), - port, _login.c_str()); - } - else - { - pkt << uint8(WOW_FAIL_SUSPENDED); - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] Temporarily banned account %s tried to login!", - ipAddress.c_str(), port, _login.c_str()); - } - } - else - { - // Get the password from the account table, upper it, and make the SRP6 calculation - std::string rI = fields[0].GetString(); - - // Don't calculate (v, s) if there are already some in the database - std::string databaseV = fields[6].GetString(); - std::string databaseS = fields[7].GetString(); - - TC_LOG_DEBUG("network", "database authentication values: v='%s' s='%s'", databaseV.c_str(), databaseS.c_str()); - - // multiply with 2 since bytes are stored as hexstring - if (databaseV.size() != size_t(BufferSizes::SRP_6_V) * 2 || databaseS.size() != size_t(BufferSizes::SRP_6_S) * 2) - SetVSFields(rI); - else - { - s.SetHexStr(databaseS.c_str()); - v.SetHexStr(databaseV.c_str()); - } - - b.SetRand(19 * 8); - BigNumber gmod = g.ModExp(b, N); - B = ((v * 3) + gmod) % N; - - ASSERT(gmod.GetNumBytes() <= 32); - - BigNumber unk3; - unk3.SetRand(16 * 8); - - // Fill the response packet with the result - if (AuthHelper::IsAcceptedClientBuild(_build)) - pkt << uint8(WOW_SUCCESS); - else - pkt << uint8(WOW_FAIL_VERSION_INVALID); - - // B may be calculated < 32B so we force minimal length to 32B - pkt.append(B.AsByteArray(32).get(), 32); // 32 bytes - pkt << uint8(1); - pkt.append(g.AsByteArray(1).get(), 1); - pkt << uint8(32); - pkt.append(N.AsByteArray(32).get(), 32); - pkt.append(s.AsByteArray(int32(BufferSizes::SRP_6_S)).get(), size_t(BufferSizes::SRP_6_S)); // 32 bytes - pkt.append(unk3.AsByteArray(16).get(), 16); - uint8 securityFlags = 0; - - // Check if token is used - _tokenKey = fields[8].GetString(); - if (!_tokenKey.empty()) - securityFlags = 4; - - pkt << uint8(securityFlags); // security flags (0x0...0x04) - - if (securityFlags & 0x01) // PIN input - { - pkt << uint32(0); - pkt << uint64(0) << uint64(0); // 16 bytes hash? - } - - if (securityFlags & 0x02) // Matrix input - { - pkt << uint8(0); - pkt << uint8(0); - pkt << uint8(0); - pkt << uint8(0); - pkt << uint64(0); - } - - if (securityFlags & 0x04) // Security token input - pkt << uint8(1); - - uint8 secLevel = fields[5].GetUInt8(); - _accountSecurityLevel = secLevel <= SEC_ADMINISTRATOR ? AccountTypes(secLevel) : SEC_ADMINISTRATOR; - - _localizationName.resize(4); - for (int i = 0; i < 4; ++i) - _localizationName[i] = challenge->country[4 - i - 1]; - - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] account %s is using '%c%c%c%c' locale (%u)", - ipAddress.c_str(), port, _login.c_str(), - challenge->country[3], challenge->country[2], challenge->country[1], challenge->country[0], - GetLocaleByName(_localizationName) - ); - } - } + // If the account is banned, reject the logon attempt + if (_accountInfo.IsBanned) + { + if (_accountInfo.IsPermanenetlyBanned) + { + pkt << uint8(WOW_FAIL_BANNED); + SendPacket(pkt); + TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] Banned account %s tried to login!", ipAddress.c_str(), port, _accountInfo.Login.c_str()); + return; + } + else + { + pkt << uint8(WOW_FAIL_SUSPENDED); + SendPacket(pkt); + TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] Temporarily banned account %s tried to login!", ipAddress.c_str(), port, _accountInfo.Login.c_str()); + return; } - else //no account - pkt << uint8(WOW_FAIL_UNKNOWN_ACCOUNT); } + // Get the password from the account table, upper it, and make the SRP6 calculation + std::string rI = fields[10].GetString(); + + // Don't calculate (v, s) if there are already some in the database + std::string databaseV = fields[11].GetString(); + std::string databaseS = fields[12].GetString(); + + TC_LOG_DEBUG("network", "database authentication values: v='%s' s='%s'", databaseV.c_str(), databaseS.c_str()); + + // multiply with 2 since bytes are stored as hexstring + if (databaseV.size() != size_t(BufferSizes::SRP_6_V) * 2 || databaseS.size() != size_t(BufferSizes::SRP_6_S) * 2) + SetVSFields(rI); + else + { + s.SetHexStr(databaseS.c_str()); + v.SetHexStr(databaseV.c_str()); + } + + b.SetRand(19 * 8); + BigNumber gmod = g.ModExp(b, N); + B = ((v * 3) + gmod) % N; + + ASSERT(gmod.GetNumBytes() <= 32); + + BigNumber unk3; + unk3.SetRand(16 * 8); + + // Fill the response packet with the result + if (AuthHelper::IsAcceptedClientBuild(_build)) + pkt << uint8(WOW_SUCCESS); + else + pkt << uint8(WOW_FAIL_VERSION_INVALID); + + // B may be calculated < 32B so we force minimal length to 32B + pkt.append(B.AsByteArray(32).get(), 32); // 32 bytes + pkt << uint8(1); + pkt.append(g.AsByteArray(1).get(), 1); + pkt << uint8(32); + pkt.append(N.AsByteArray(32).get(), 32); + pkt.append(s.AsByteArray(int32(BufferSizes::SRP_6_S)).get(), size_t(BufferSizes::SRP_6_S)); // 32 bytes + pkt.append(unk3.AsByteArray(16).get(), 16); + uint8 securityFlags = 0; + + // Check if token is used + _tokenKey = fields[9].GetString(); + if (!_tokenKey.empty()) + securityFlags = 4; + + pkt << uint8(securityFlags); // security flags (0x0...0x04) + + if (securityFlags & 0x01) // PIN input + { + pkt << uint32(0); + pkt << uint64(0) << uint64(0); // 16 bytes hash? + } + + if (securityFlags & 0x02) // Matrix input + { + pkt << uint8(0); + pkt << uint8(0); + pkt << uint8(0); + pkt << uint8(0); + pkt << uint64(0); + } + + if (securityFlags & 0x04) // Security token input + pkt << uint8(1); + + TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] account %s is using '%s' locale (%u)", + ipAddress.c_str(), port, _accountInfo.Login.c_str(), _localizationName.c_str(), GetLocaleByName(_localizationName)); + SendPacket(pkt); - return true; } // Logon Proof command handler bool AuthSession::HandleLogonProof() { - TC_LOG_DEBUG("server.authserver", "Entering _HandleLogonProof"); + if (_sentProof) + return false; + + _sentProof = true; + // Read the packet sAuthLogonProof_C *logonProof = reinterpret_cast<sAuthLogonProof_C*>(GetReadBuffer().GetReadPointer()); @@ -431,7 +499,7 @@ bool AuthSession::HandleLogonProof() A.SetBinary(logonProof->A, 32); // SRP safeguard: abort if A == 0 - if (A.isZero()) + if (A.IsZero()) { return false; } @@ -487,7 +555,7 @@ bool AuthSession::HandleLogonProof() t3.SetBinary(hash, 20); sha.Initialize(); - sha.UpdateData(_login); + sha.UpdateData(_accountInfo.Login); sha.Finalize(); uint8 t4[SHA_DIGEST_LENGTH]; memcpy(t4, sha.GetDigest(), SHA_DIGEST_LENGTH); @@ -503,22 +571,19 @@ bool AuthSession::HandleLogonProof() // Check if SRP6 results match (password is correct), else send an error if (!memcmp(M.AsByteArray(sha.GetLength()).get(), logonProof->M1, 20)) { - TC_LOG_DEBUG("server.authserver", "'%s:%d' User '%s' successfully authenticated", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _login.c_str()); + TC_LOG_DEBUG("server.authserver", "'%s:%d' User '%s' successfully authenticated", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo.Login.c_str()); // Update the sessionkey, last_ip, last login time and reset number of failed logins in the account table for this account // No SQL injection (escaped user name) and IP address as received by socket - const char *K_hex = K.AsHexStr(); PreparedStatement *stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LOGONPROOF); - stmt->setString(0, K_hex); + stmt->setString(0, K.AsHexStr()); stmt->setString(1, GetRemoteIpAddress().to_string().c_str()); stmt->setUInt32(2, GetLocaleByName(_localizationName)); stmt->setString(3, _os); - stmt->setString(4, _login); + stmt->setString(4, _accountInfo.Login); LoginDatabase.DirectExecute(stmt); - OPENSSL_free((void*)K_hex); - // Finish SRP6 and send the final result to the client sha.Initialize(); sha.UpdateBigNumbers(&A, &M, &K, NULL); @@ -531,6 +596,7 @@ bool AuthSession::HandleLogonProof() std::string token(reinterpret_cast<char*>(GetReadBuffer().GetReadPointer() + sizeof(sAuthLogonProof_C) + sizeof(size)), size); GetReadBuffer().ReadCompleted(sizeof(size) + size); uint32 validToken = TOTP::GenerateToken(_tokenKey.c_str()); + _tokenKey.clear(); uint32 incomingToken = atoi(token.c_str()); if (validToken != incomingToken) { @@ -571,7 +637,7 @@ bool AuthSession::HandleLogonProof() } SendPacket(packet); - _isAuthenticated = true; + _status = STATUS_AUTHED; } else { @@ -583,7 +649,7 @@ bool AuthSession::HandleLogonProof() SendPacket(packet); TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] account %s tried to login with invalid password!", - GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _login.c_str()); + GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo.Login.c_str()); uint32 MaxWrongPassCount = sConfigMgr->GetIntDefault("WrongPass.MaxCount", 0); @@ -591,7 +657,7 @@ bool AuthSession::HandleLogonProof() if (sConfigMgr->GetBoolDefault("WrongPass.Logging", false)) { PreparedStatement* logstmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_FALP_IP_LOGGING); - logstmt->setString(0, _login); + logstmt->setString(0, _accountInfo.Login); logstmt->setString(1, GetRemoteIpAddress().to_string()); logstmt->setString(2, "Logged on failed AccountLogin due wrong password"); @@ -602,42 +668,33 @@ bool AuthSession::HandleLogonProof() { //Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_FAILEDLOGINS); - stmt->setString(0, _login); + stmt->setString(0, _accountInfo.Login); LoginDatabase.Execute(stmt); - stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_FAILEDLOGINS); - stmt->setString(0, _login); - - if (PreparedQueryResult loginfail = LoginDatabase.Query(stmt)) + if (_accountInfo.FailedLogins >= MaxWrongPassCount) { - uint32 failed_logins = (*loginfail)[1].GetUInt32(); + uint32 WrongPassBanTime = sConfigMgr->GetIntDefault("WrongPass.BanTime", 600); + bool WrongPassBanType = sConfigMgr->GetBoolDefault("WrongPass.BanType", false); - if (failed_logins >= MaxWrongPassCount) + if (WrongPassBanType) { - uint32 WrongPassBanTime = sConfigMgr->GetIntDefault("WrongPass.BanTime", 600); - bool WrongPassBanType = sConfigMgr->GetBoolDefault("WrongPass.BanType", false); - - if (WrongPassBanType) - { - uint32 acc_id = (*loginfail)[0].GetUInt32(); - stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED); - stmt->setUInt32(0, acc_id); - stmt->setUInt32(1, WrongPassBanTime); - LoginDatabase.Execute(stmt); - - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times", - GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _login.c_str(), WrongPassBanTime, failed_logins); - } - else - { - stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_IP_AUTO_BANNED); - stmt->setString(0, GetRemoteIpAddress().to_string()); - stmt->setUInt32(1, WrongPassBanTime); - LoginDatabase.Execute(stmt); - - TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] IP got banned for '%u' seconds because account %s failed to authenticate '%u' times", - GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), WrongPassBanTime, _login.c_str(), failed_logins); - } + stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED); + stmt->setUInt32(0, _accountInfo.Id); + stmt->setUInt32(1, WrongPassBanTime); + LoginDatabase.Execute(stmt); + + TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times", + GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo.Login.c_str(), WrongPassBanTime, _accountInfo.FailedLogins); + } + else + { + stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_IP_AUTO_BANNED); + stmt->setString(0, GetRemoteIpAddress().to_string()); + stmt->setUInt32(1, WrongPassBanTime); + LoginDatabase.Execute(stmt); + + TC_LOG_DEBUG("server.authserver", "'%s:%d' [AuthChallenge] IP got banned for '%u' seconds because account %s failed to authenticate '%u' times", + GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), WrongPassBanTime, _accountInfo.Login.c_str(), _accountInfo.FailedLogins); } } } @@ -648,61 +705,88 @@ bool AuthSession::HandleLogonProof() bool AuthSession::HandleReconnectChallenge() { - TC_LOG_DEBUG("server.authserver", "Entering _HandleReconnectChallenge"); - sAuthLogonChallenge_C* challenge = reinterpret_cast<sAuthLogonChallenge_C*>(GetReadBuffer().GetReadPointer()); + if (_sentChallenge) + return false; - //TC_LOG_DEBUG("server.authserver", "[AuthChallenge] got full packet, %#04x bytes", challenge->size); - TC_LOG_DEBUG("server.authserver", "[AuthChallenge] name(%d): '%s'", challenge->I_len, challenge->I); + _sentChallenge = true; - _login.assign((const char*)challenge->I, challenge->I_len); + sAuthLogonChallenge_C* challenge = reinterpret_cast<sAuthLogonChallenge_C*>(GetReadBuffer().GetReadPointer()); + if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) + return false; - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SESSIONKEY); - stmt->setString(0, _login); - PreparedQueryResult result = LoginDatabase.Query(stmt); + std::string login((const char*)challenge->I, challenge->I_len); + TC_LOG_DEBUG("server.authserver", "[ReconnectChallenge] '%s'", login.c_str()); - // Stop if the account is not found - if (!result) + if (_queryCallback) { - TC_LOG_ERROR("server.authserver", "'%s:%d' [ERROR] user %s tried to login and we cannot find his session key in the database.", - GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _login.c_str()); - return false; + ByteBuffer pkt; + pkt << uint8(AUTH_RECONNECT_CHALLENGE); + pkt << uint8(WOW_FAIL_DB_BUSY); + SendPacket(pkt); + + TC_LOG_DEBUG("server.authserver", "[ReconnectChallenge] %s attempted to log too quick after previous attempt!", login.c_str()); + return true; } - // Reinitialize build, expansion and the account securitylevel _build = challenge->build; _expversion = uint8(AuthHelper::IsPostBCAcceptedClientBuild(_build) ? POST_BC_EXP_FLAG : (AuthHelper::IsPreBCAcceptedClientBuild(_build) ? PRE_BC_EXP_FLAG : NO_VALID_EXP_FLAG)); - _os = (const char*)challenge->os; - - if (_os.size() > 4) - return false; + std::array<char, 5> os; + os.fill('\0'); + memcpy(os.data(), challenge->os, sizeof(challenge->os)); + _os = os.data(); // Restore string order as its byte order is reversed std::reverse(_os.begin(), _os.end()); - Field* fields = result->Fetch(); - uint8 secLevel = fields[2].GetUInt8(); - _accountSecurityLevel = secLevel <= SEC_ADMINISTRATOR ? AccountTypes(secLevel) : SEC_ADMINISTRATOR; + _localizationName.resize(4); + for (int i = 0; i < 4; ++i) + _localizationName[i] = challenge->country[4 - i - 1]; - K.SetHexStr((*result)[0].GetCString()); + // Get the account details from the account table + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RECONNECTCHALLENGE); + stmt->setString(0, login); - // Sending response + _queryCallback = std::bind(&AuthSession::ReconnectChallengeCallback, this, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); + return true; +} + +void AuthSession::ReconnectChallengeCallback(PreparedQueryResult result) +{ ByteBuffer pkt; pkt << uint8(AUTH_RECONNECT_CHALLENGE); - pkt << uint8(0x00); + + if (!result) + { + pkt << uint8(WOW_FAIL_UNKNOWN_ACCOUNT); + SendPacket(pkt); + return; + } + + Field* fields = result->Fetch(); + + _accountInfo.LoadResult(fields); + K.SetHexStr(fields[9].GetCString()); _reconnectProof.SetRand(16 * 8); - pkt.append(_reconnectProof.AsByteArray(16).get(), 16); // 16 bytes random + + pkt << uint8(WOW_SUCCESS); + pkt.append(_reconnectProof.AsByteArray(16).get(), 16); // 16 bytes random pkt << uint64(0x00) << uint64(0x00); // 16 bytes zeros SendPacket(pkt); - - return true; } + bool AuthSession::HandleReconnectProof() { TC_LOG_DEBUG("server.authserver", "Entering _HandleReconnectProof"); + if (_sentProof) + return false; + + _sentProof = true; + sAuthReconnectProof_C *reconnectProof = reinterpret_cast<sAuthReconnectProof_C*>(GetReadBuffer().GetReadPointer()); - if (_login.empty() || !_reconnectProof.GetNumBytes() || !K.GetNumBytes()) + if (_accountInfo.Login.empty() || !_reconnectProof.GetNumBytes() || !K.GetNumBytes()) return false; BigNumber t1; @@ -710,7 +794,7 @@ bool AuthSession::HandleReconnectProof() SHA1Hash sha; sha.Initialize(); - sha.UpdateData(_login); + sha.UpdateData(_accountInfo.Login); sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, NULL); sha.Finalize(); @@ -722,87 +806,60 @@ bool AuthSession::HandleReconnectProof() pkt << uint8(0x00); pkt << uint16(0x00); // 2 bytes zeros SendPacket(pkt); - _isAuthenticated = true; + _status = STATUS_AUTHED; return true; } else { TC_LOG_ERROR("server.authserver", "'%s:%d' [ERROR] user %s tried to login, but session is invalid.", GetRemoteIpAddress().to_string().c_str(), - GetRemotePort(), _login.c_str()); + GetRemotePort(), _accountInfo.Login.c_str()); return false; } } -tcp::endpoint const GetAddressForClient(Realm const& realm, ip::address const& clientAddr) +bool AuthSession::HandleRealmList() { - ip::address realmIp; + TC_LOG_DEBUG("server.authserver", "Entering _HandleRealmList"); - // Attempt to send best address for client - if (clientAddr.is_loopback()) + if (_queryCallback) { - // Try guessing if realm is also connected locally - if (realm.LocalAddress.is_loopback() || realm.ExternalAddress.is_loopback()) - realmIp = clientAddr; - else - { - // Assume that user connecting from the machine that authserver is located on - // has all realms available in his local network - realmIp = realm.LocalAddress; - } - } - else - { - if (clientAddr.is_v4() && - (clientAddr.to_v4().to_ulong() & realm.LocalSubnetMask.to_v4().to_ulong()) == - (realm.LocalAddress.to_v4().to_ulong() & realm.LocalSubnetMask.to_v4().to_ulong())) - { - realmIp = realm.LocalAddress; - } - else - realmIp = realm.ExternalAddress; + TC_LOG_DEBUG("server.authserver", "[RealmList] %s attempted to get realmlist too quick after previous attempt!", _accountInfo.Login.c_str()); + return false; } - tcp::endpoint endpoint(realmIp, realm.port); + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS); + stmt->setUInt32(0, _accountInfo.Id); - // Return external IP - return endpoint; + _queryCallback = std::bind(&AuthSession::RealmListCallback, this, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); + return true; } -bool AuthSession::HandleRealmList() +void AuthSession::RealmListCallback(PreparedQueryResult result) { - TC_LOG_DEBUG("server.authserver", "Entering _HandleRealmList"); - - // Get the user id (else close the connection) - // No SQL injection (prepared statement) - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ID_BY_NAME); - stmt->setString(0, _login); - PreparedQueryResult result = LoginDatabase.Query(stmt); - if (!result) + std::map<uint32, uint8> characterCounts; + if (result) { - TC_LOG_ERROR("server.authserver", "'%s:%d' [ERROR] user %s tried to login but we cannot find him in the database.", GetRemoteIpAddress().to_string().c_str(), - GetRemotePort(), _login.c_str()); - return false; + do + { + Field* fields = result->Fetch(); + characterCounts[fields[0].GetUInt32()] = fields[1].GetUInt8(); + } while (result->NextRow()); } - Field* fields = result->Fetch(); - uint32 id = fields[0].GetUInt32(); - - // Update realm list if need - sRealmList->UpdateIfNeed(); - // Circle through realms in the RealmList and construct the return packet (including # of user characters in each realm) ByteBuffer pkt; size_t RealmListSize = 0; - for (RealmList::RealmMap::const_iterator i = sRealmList->begin(); i != sRealmList->end(); ++i) + for (RealmList::RealmMap::value_type const& i : sRealmList->GetRealms()) { - const Realm &realm = i->second; + const Realm &realm = i.second; // don't work with realms which not compatible with the client - bool okBuild = ((_expversion & POST_BC_EXP_FLAG) && realm.gamebuild == _build) || ((_expversion & PRE_BC_EXP_FLAG) && !AuthHelper::IsPreBCAcceptedClientBuild(realm.gamebuild)); + bool okBuild = ((_expversion & POST_BC_EXP_FLAG) && realm.Build == _build) || ((_expversion & PRE_BC_EXP_FLAG) && !AuthHelper::IsPreBCAcceptedClientBuild(realm.Build)); // No SQL injection. id of realm is controlled by the database. - uint32 flag = realm.flag; - RealmBuildInfo const* buildInfo = AuthHelper::GetBuildInfo(realm.gamebuild); + uint32 flag = realm.Flags; + RealmBuildInfo const* buildInfo = AuthHelper::GetBuildInfo(realm.Build); if (!okBuild) { if (!buildInfo) @@ -814,7 +871,7 @@ bool AuthSession::HandleRealmList() if (!buildInfo) flag &= ~REALM_FLAG_SPECIFYBUILD; - std::string name = i->first; + std::string name = realm.Name; if (_expversion & PRE_BC_EXP_FLAG && flag & REALM_FLAG_SPECIFYBUILD) { std::ostringstream ss; @@ -822,27 +879,19 @@ bool AuthSession::HandleRealmList() name = ss.str(); } - uint8 lock = (realm.allowedSecurityLevel > _accountSecurityLevel) ? 1 : 0; - - uint8 AmountOfCharacters = 0; - stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_NUM_CHARS_ON_REALM); - stmt->setUInt32(0, realm.m_ID); - stmt->setUInt32(1, id); - result = LoginDatabase.Query(stmt); - if (result) - AmountOfCharacters = (*result)[0].GetUInt8(); + uint8 lock = (realm.AllowedSecurityLevel > _accountInfo.SecurityLevel) ? 1 : 0; - pkt << realm.icon; // realm type + pkt << uint8(realm.Type); // realm type if (_expversion & POST_BC_EXP_FLAG) // only 2.x and 3.x clients - pkt << lock; // if 1, then realm locked + pkt << uint8(lock); // if 1, then realm locked pkt << uint8(flag); // RealmFlags pkt << name; - pkt << boost::lexical_cast<std::string>(GetAddressForClient(realm, GetRemoteIpAddress())); - pkt << realm.populationLevel; - pkt << AmountOfCharacters; - pkt << realm.timezone; // realm category + pkt << boost::lexical_cast<std::string>(realm.GetAddressForClient(GetRemoteIpAddress())); + pkt << float(realm.PopulationLevel); + pkt << uint8(characterCounts[realm.Id.Realm]); + pkt << uint8(realm.Timezone); // realm category if (_expversion & POST_BC_EXP_FLAG) // 2.x and 3.x clients - pkt << uint8(realm.m_ID); + pkt << uint8(realm.Id.Realm); else pkt << uint8(0x0); // 1.12.1 and 1.12.2 clients @@ -882,32 +931,6 @@ bool AuthSession::HandleRealmList() hdr.append(RealmListSizeBuffer); // append RealmList's size buffer hdr.append(pkt); // append realms in the realmlist SendPacket(hdr); - return true; -} - -// Resume patch transfer -bool AuthSession::HandleXferResume() -{ - TC_LOG_DEBUG("server.authserver", "Entering _HandleXferResume"); - //uint8 - //uint64 - return true; -} - -// Cancel patch transfer -bool AuthSession::HandleXferCancel() -{ - TC_LOG_DEBUG("server.authserver", "Entering _HandleXferCancel"); - //uint8 - return false; -} - -// Accept patch transfer -bool AuthSession::HandleXferAccept() -{ - TC_LOG_DEBUG("server.authserver", "Entering _HandleXferAccept"); - //uint8 - return true; } // Make the SRP6 calculation from hash in dB @@ -933,16 +956,9 @@ void AuthSession::SetVSFields(const std::string& rI) v = g.ModExp(x, N); // No SQL injection (username escaped) - char *v_hex, *s_hex; - v_hex = v.AsHexStr(); - s_hex = s.AsHexStr(); - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_VS); - stmt->setString(0, v_hex); - stmt->setString(1, s_hex); - stmt->setString(2, _login); + stmt->setString(0, v.AsHexStr()); + stmt->setString(1, s.AsHexStr()); + stmt->setString(2, _accountInfo.Login); LoginDatabase.Execute(stmt); - - OPENSSL_free(v_hex); - OPENSSL_free(s_hex); } diff --git a/src/server/authserver/Server/AuthSession.h b/src/server/authserver/Server/AuthSession.h index d40e0852b57..027011629eb 100644 --- a/src/server/authserver/Server/AuthSession.h +++ b/src/server/authserver/Server/AuthSession.h @@ -23,29 +23,48 @@ #include "ByteBuffer.h" #include "Socket.h" #include "BigNumber.h" +#include "QueryCallback.h" #include <memory> #include <boost/asio/ip/tcp.hpp> using boost::asio::ip::tcp; +class Field; struct AuthHandler; +enum AuthStatus +{ + STATUS_CONNECTED = 0, + STATUS_AUTHED +}; + +struct AccountInfo +{ + void LoadResult(Field* fields); + + uint32 Id = 0; + std::string Login; + bool IsLockedToIP = false; + std::string LockCountry; + std::string LastIP; + uint32 FailedLogins = 0; + bool IsBanned = false; + bool IsPermanenetlyBanned = false; + AccountTypes SecurityLevel = SEC_PLAYER; + std::string TokenKey; +}; + class AuthSession : public Socket<AuthSession> { + typedef Socket<AuthSession> AuthSocket; + public: static std::unordered_map<uint8, AuthHandler> InitHandlers(); - AuthSession(tcp::socket&& socket) : Socket(std::move(socket)), - _isAuthenticated(false), _build(0), _expversion(0), _accountSecurityLevel(SEC_PLAYER) - { - N.SetHexStr("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7"); - g.SetDword(7); - } + AuthSession(tcp::socket&& socket); - void Start() override - { - AsyncRead(); - } + void Start() override; + bool Update() override; void SendPacket(ByteBuffer& packet); @@ -59,10 +78,10 @@ private: bool HandleReconnectProof(); bool HandleRealmList(); - //data transfer handle for patch - bool HandleXferResume(); - bool HandleXferCancel(); - bool HandleXferAccept(); + void CheckIpCallback(PreparedQueryResult result); + void LogonChallengeCallback(PreparedQueryResult result); + void ReconnectChallengeCallback(PreparedQueryResult result); + void RealmListCallback(PreparedQueryResult result); void SetVSFields(const std::string& rI); @@ -71,22 +90,27 @@ private: BigNumber K; BigNumber _reconnectProof; - bool _isAuthenticated; + bool _sentChallenge; + bool _sentProof; + + AuthStatus _status; + AccountInfo _accountInfo; std::string _tokenKey; - std::string _login; std::string _localizationName; std::string _os; + std::string _ipCountry; uint16 _build; uint8 _expversion; - AccountTypes _accountSecurityLevel; + PreparedQueryResultFuture _queryFuture; + std::function<void(PreparedQueryResult)> _queryCallback; }; #pragma pack(push, 1) struct AuthHandler { - uint32 status; + AuthStatus status; size_t packetSize; bool (AuthSession::*handler)(); }; diff --git a/src/server/authserver/Server/AuthSocketMgr.h b/src/server/authserver/Server/AuthSocketMgr.h index fa96502663f..9923f2b2f11 100644 --- a/src/server/authserver/Server/AuthSocketMgr.h +++ b/src/server/authserver/Server/AuthSocketMgr.h @@ -21,8 +21,6 @@ #include "SocketMgr.h" #include "AuthSession.h" -void OnSocketAccept(tcp::socket&& sock); - class AuthSocketMgr : public SocketMgr<AuthSession> { typedef SocketMgr<AuthSession> BaseSocketMgr; @@ -34,12 +32,12 @@ public: return instance; } - bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port) override + bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount = 1) override { - if (!BaseSocketMgr::StartNetwork(service, bindIp, port)) + if (!BaseSocketMgr::StartNetwork(service, bindIp, port, threadCount)) return false; - _acceptor->AsyncAcceptManaged(&OnSocketAccept); + _acceptor->AsyncAcceptWithCallback<&AuthSocketMgr::OnSocketAccept>(); return true; } @@ -48,14 +46,13 @@ protected: { return new NetworkThread<AuthSession>[1]; } + + static void OnSocketAccept(tcp::socket&& sock, uint32 threadIndex) + { + Instance().OnSocketOpen(std::forward<tcp::socket>(sock), threadIndex); + } }; #define sAuthSocketMgr AuthSocketMgr::Instance() -void OnSocketAccept(tcp::socket&& sock) -{ - sAuthSocketMgr.OnSocketOpen(std::forward<tcp::socket>(sock)); -} - - #endif // AuthSocketMgr_h__ diff --git a/src/server/authserver/authserver.conf.dist b/src/server/authserver/authserver.conf.dist index 604988d62e5..1d3b48839a8 100644 --- a/src/server/authserver/authserver.conf.dist +++ b/src/server/authserver/authserver.conf.dist @@ -131,6 +131,33 @@ WrongPass.BanType = 0 WrongPass.Logging = 0 # +# BanExpiryCheckInterval +# Description: Time (in seconds) between checks for expired bans +# Default: 60 + +BanExpiryCheckInterval = 60 + +# +# SourceDirectory +# Description: The path to your TrinityCore source directory. +# If the path is left empty, the built-in CMAKE_SOURCE_DIR is used. +# Example: "../TrinityCore" +# Default: "" + +SourceDirectory = "" + +# +# MySQLExecutable +# Description: The path to your mysql cli binary. +# If the path is left empty, built-in path from cmake is used. +# Example: "C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql.exe" +# "mysql.exe" +# "/usr/bin/mysql" +# Default: "" + +MySQLExecutable = "" + +# ################################################################################################### ################################################################################################### @@ -152,11 +179,19 @@ LoginDatabaseInfo = "127.0.0.1;3306;trinity;trinity;auth" # LoginDatabase.WorkerThreads # Description: The amount of worker threads spawned to handle asynchronous (delayed) MySQL # statements. Each worker thread is mirrored with its own connection to the +# MySQL server and their own thread on the MySQL server. # Default: 1 LoginDatabase.WorkerThreads = 1 # +# LoginDatabase.SynchThreads +# Description: The amount of MySQL connections spawned to handle. +# Default: 1 - (LoginDatabase.WorkerThreads) + +LoginDatabase.SynchThreads = 1 + +# ################################################################################################### ################################################################################################### @@ -174,26 +209,6 @@ LoginDatabase.WorkerThreads = 1 Updates.EnableDatabases = 0 # -# Updates.SourcePath -# Description: The path to your TrinityCore source directory. -# If the path is left empty, built-in CMAKE_SOURCE_DIR is used. -# Example: "../TrinityCore" -# Default: "" - -Updates.SourcePath = "" - -# -# Updates.MySqlCLIPath -# Description: The path to your mysql cli binary. -# If the path is left empty, built-in path from cmake is used. -# Example: "C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql.exe" -# "mysql.exe" -# "/usr/bin/mysql" -# Default: "" - -Updates.MySqlCLIPath = "" - -# # Updates.AutoSetup # Description: Auto populate empty databases. # Default: 1 - (Enabled) diff --git a/src/server/database/CMakeLists.txt b/src/server/database/CMakeLists.txt index 5a53899f4cb..bd2fa280ad6 100644 --- a/src/server/database/CMakeLists.txt +++ b/src/server/database/CMakeLists.txt @@ -8,34 +8,22 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -if (NOT MYSQL_FOUND) - message(SEND_ERROR "MySQL wasn't found on your system but it's required to build the servers!") -endif() - -if( USE_COREPCH ) - include_directories(${CMAKE_CURRENT_BINARY_DIR}) -endif() - -file(GLOB_RECURSE sources_Database Database/*.cpp Database/*.h) -file(GLOB_RECURSE sources_Logging Logging/*.cpp Logging/*.h) -file(GLOB_RECURSE sources_Updater Updater/*.cpp Updater/*.h) - -file(GLOB sources_localdir *.cpp *.h) - -# -# Build shared sourcelist -# +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) if (USE_COREPCH) - set(database_STAT_PCH_HDR PrecompiledHeaders/databasePCH.h) - set(database_STAT_PCH_SRC PrecompiledHeaders/databasePCH.cpp) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/databasePCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/databasePCH.cpp) endif() -set(database_STAT_SRCS - ${database_STAT_SRCS} - ${sources_Database} - ${sources_Logging} - ${sources_Updater} +GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) + +add_library(database + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES} ) # Do NOT add any extra include directory unless it does not create unneeded extra dependencies, @@ -47,31 +35,43 @@ set(database_STAT_SRCS # linkage (enums, defines...) it is discouraged to do so unless necessary, as it will pullute # include_directories leading to further unnoticed dependency aditions # Linker Depencency requirements: common -include_directories( +CollectIncludeDirectories( ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/Database - ${CMAKE_CURRENT_SOURCE_DIR}/Updater - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/process - ${CMAKE_SOURCE_DIR}/src/common/ - ${CMAKE_SOURCE_DIR}/src/common/Configuration - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${MYSQL_INCLUDE_DIR} - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) -GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) +target_include_directories(database + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) -add_library(database STATIC - ${database_STAT_SRCS} - ${database_STAT_PCH_SRC} -) +add_definitions(-DTRINITY_API_EXPORT_DATABASE) + +target_link_libraries(database + PUBLIC + common + mysql) + +set_target_properties(database + PROPERTIES + FOLDER + "server") + +if( BUILD_SHARED_LIBS ) + if( UNIX ) + install(TARGETS database + LIBRARY + DESTINATION lib) + elseif( WIN32 ) + install(TARGETS database + RUNTIME + DESTINATION "${CMAKE_INSTALL_PREFIX}") + endif() +endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(database ${database_STAT_PCH_HDR} ${database_STAT_PCH_SRC}) + add_cxx_pch(database ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif () diff --git a/src/server/database/Database/AdhocStatement.h b/src/server/database/Database/AdhocStatement.h index ab85493a14e..9315038bce1 100644 --- a/src/server/database/Database/AdhocStatement.h +++ b/src/server/database/Database/AdhocStatement.h @@ -25,7 +25,7 @@ typedef std::future<QueryResult> QueryResultFuture; typedef std::promise<QueryResult> QueryResultPromise; /*! Raw, ad-hoc query. */ -class BasicStatementTask : public SQLOperation +class TC_DATABASE_API BasicStatementTask : public SQLOperation { public: BasicStatementTask(const char* sql, bool async = false); diff --git a/src/server/database/Database/DatabaseEnv.cpp b/src/server/database/Database/DatabaseEnv.cpp new file mode 100644 index 00000000000..3b2e632e4fb --- /dev/null +++ b/src/server/database/Database/DatabaseEnv.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "DatabaseEnv.h" + +WorldDatabaseWorkerPool WorldDatabase; +CharacterDatabaseWorkerPool CharacterDatabase; +LoginDatabaseWorkerPool LoginDatabase; diff --git a/src/server/database/Database/DatabaseEnv.h b/src/server/database/Database/DatabaseEnv.h index cc8355a1302..05a4d5aad75 100644 --- a/src/server/database/Database/DatabaseEnv.h +++ b/src/server/database/Database/DatabaseEnv.h @@ -38,9 +38,11 @@ #include "Implementation/CharacterDatabase.h" #include "Implementation/WorldDatabase.h" -extern WorldDatabaseWorkerPool WorldDatabase; -extern CharacterDatabaseWorkerPool CharacterDatabase; -extern LoginDatabaseWorkerPool LoginDatabase; +/// Accessor to the world database +TC_DATABASE_API extern WorldDatabaseWorkerPool WorldDatabase; +/// Accessor to the character database +TC_DATABASE_API extern CharacterDatabaseWorkerPool CharacterDatabase; +/// Accessor to the realm/login database +TC_DATABASE_API extern LoginDatabaseWorkerPool LoginDatabase; #endif - diff --git a/src/server/database/Database/DatabaseLoader.cpp b/src/server/database/Database/DatabaseLoader.cpp index 92d8730cd12..f358bdd54b4 100644 --- a/src/server/database/Database/DatabaseLoader.cpp +++ b/src/server/database/Database/DatabaseLoader.cpp @@ -32,7 +32,7 @@ DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool<T>& pool, std::st { bool const updatesEnabledForThis = DBUpdater<T>::IsEnabled(_updateFlags); - _open.push(std::make_pair([this, name, updatesEnabledForThis, &pool]() -> bool + _open.push([this, name, updatesEnabledForThis, &pool]() -> bool { std::string const dbString = sConfigMgr->GetStringDefault(name + "DatabaseInfo", ""); if (dbString.empty()) @@ -71,12 +71,13 @@ DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool<T>& pool, std::st return false; } } + // Add the close operation + _close.push([&pool] + { + pool.Close(); + }); return true; - }, - [&pool]() - { - pool.Close(); - })); + }); // Populate and update only if updates are enabled for this pool if (updatesEnabledForThis) @@ -137,38 +138,7 @@ bool DatabaseLoader::Load() bool DatabaseLoader::OpenDatabases() { - while (!_open.empty()) - { - std::pair<Predicate, std::function<void()>> const load = _open.top(); - if (load.first()) - _close.push(load.second); - else - { - // Close all loaded databases - while (!_close.empty()) - { - _close.top()(); - _close.pop(); - } - return false; - } - - _open.pop(); - } - return true; -} - -// Processes the elements of the given stack until a predicate returned false. -bool DatabaseLoader::Process(std::stack<Predicate>& stack) -{ - while (!stack.empty()) - { - if (!stack.top()()) - return false; - - stack.pop(); - } - return true; + return Process(_open); } bool DatabaseLoader::PopulateDatabases() @@ -186,9 +156,30 @@ bool DatabaseLoader::PrepareStatements() return Process(_prepare); } -template -DatabaseLoader& DatabaseLoader::AddDatabase<LoginDatabaseConnection>(DatabaseWorkerPool<LoginDatabaseConnection>& pool, std::string const& name); -template -DatabaseLoader& DatabaseLoader::AddDatabase<WorldDatabaseConnection>(DatabaseWorkerPool<WorldDatabaseConnection>& pool, std::string const& name); -template -DatabaseLoader& DatabaseLoader::AddDatabase<CharacterDatabaseConnection>(DatabaseWorkerPool<CharacterDatabaseConnection>& pool, std::string const& name); +bool DatabaseLoader::Process(std::queue<Predicate>& queue) +{ + while (!queue.empty()) + { + if (!queue.front()()) + { + // Close all open databases which have a registered close operation + while (!_close.empty()) + { + _close.top()(); + _close.pop(); + } + + return false; + } + + queue.pop(); + } + return true; +} + +template TC_DATABASE_API +DatabaseLoader& DatabaseLoader::AddDatabase<LoginDatabaseConnection>(LoginDatabaseWorkerPool&, std::string const&); +template TC_DATABASE_API +DatabaseLoader& DatabaseLoader::AddDatabase<CharacterDatabaseConnection>(CharacterDatabaseWorkerPool&, std::string const&); +template TC_DATABASE_API +DatabaseLoader& DatabaseLoader::AddDatabase<WorldDatabaseConnection>(WorldDatabaseWorkerPool&, std::string const&); diff --git a/src/server/database/Database/DatabaseLoader.h b/src/server/database/Database/DatabaseLoader.h index da92cf85a9f..647c1e113e3 100644 --- a/src/server/database/Database/DatabaseLoader.h +++ b/src/server/database/Database/DatabaseLoader.h @@ -19,14 +19,15 @@ #define DatabaseLoader_h__ #include "DatabaseWorkerPool.h" -#include "DatabaseEnv.h" +#include "DBUpdater.h" -#include <stack> #include <functional> +#include <stack> +#include <queue> // A helper class to initiate all database worker pools, // handles updating, delays preparing of statements and cleans up on failure. -class DatabaseLoader +class TC_DATABASE_API DatabaseLoader { public: DatabaseLoader(std::string const& logger, uint32 const defaultUpdateMask); @@ -56,16 +57,18 @@ private: bool PrepareStatements(); using Predicate = std::function<bool()>; + using Closer = std::function<void()>; - static bool Process(std::stack<Predicate>& stack); + // Invokes all functions in the given queue and closes the databases on errors. + // Returns false when there was an error. + bool Process(std::queue<Predicate>& queue); std::string const _logger; bool const _autoSetup; uint32 const _updateFlags; - std::stack<std::pair<Predicate, std::function<void()>>> _open; - std::stack<std::function<void()>> _close; - std::stack<Predicate> _populate, _update, _prepare; + std::queue<Predicate> _open, _populate, _update, _prepare; + std::stack<Closer> _close; }; #endif // DatabaseLoader_h__ diff --git a/src/server/database/Database/DatabaseWorker.h b/src/server/database/Database/DatabaseWorker.h index c21a3d2a343..d6b43943f7d 100644 --- a/src/server/database/Database/DatabaseWorker.h +++ b/src/server/database/Database/DatabaseWorker.h @@ -24,7 +24,7 @@ class MySQLConnection; class SQLOperation; -class DatabaseWorker +class TC_DATABASE_API DatabaseWorker { public: DatabaseWorker(ProducerConsumerQueue<SQLOperation*>* newQueue, MySQLConnection* connection); diff --git a/src/server/database/Database/DatabaseWorkerPool.cpp b/src/server/database/Database/DatabaseWorkerPool.cpp new file mode 100644 index 00000000000..6fc4dc21a51 --- /dev/null +++ b/src/server/database/Database/DatabaseWorkerPool.cpp @@ -0,0 +1,322 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "DatabaseWorkerPool.h" +#include "DatabaseEnv.h" + +#define MIN_MYSQL_SERVER_VERSION 50100u +#define MIN_MYSQL_CLIENT_VERSION 50100u + +template <class T> +DatabaseWorkerPool<T>::DatabaseWorkerPool() + : _queue(new ProducerConsumerQueue<SQLOperation*>()), + _async_threads(0), _synch_threads(0) +{ + WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe."); + WPFatal(mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION, "TrinityCore does not support MySQL versions below 5.1"); + WPFatal(mysql_get_client_version() == MYSQL_VERSION_ID, "Used MySQL library version (%s) does not match the version used to compile TrinityCore (%s). Search on forum for TCE00011.", + mysql_get_client_info(), MYSQL_SERVER_VERSION); +} + +template <class T> +void DatabaseWorkerPool<T>::SetConnectionInfo(std::string const& infoString, + uint8 const asyncThreads, uint8 const synchThreads) +{ + _connectionInfo = Trinity::make_unique<MySQLConnectionInfo>(infoString); + + _async_threads = asyncThreads; + _synch_threads = synchThreads; +} + +template <class T> +uint32 DatabaseWorkerPool<T>::Open() +{ + WPFatal(_connectionInfo.get(), "Connection info was not set!"); + + TC_LOG_INFO("sql.driver", "Opening DatabasePool '%s'. " + "Asynchronous connections: %u, synchronous connections: %u.", + GetDatabaseName(), _async_threads, _synch_threads); + + uint32 error = OpenConnections(IDX_ASYNC, _async_threads); + + if (error) + return error; + + error = OpenConnections(IDX_SYNCH, _synch_threads); + + if (!error) + { + TC_LOG_INFO("sql.driver", "DatabasePool '%s' opened successfully. " SZFMTD + " total connections running.", GetDatabaseName(), + (_connections[IDX_SYNCH].size() + _connections[IDX_ASYNC].size())); + } + + return error; +} + +template <class T> +void DatabaseWorkerPool<T>::Close() +{ + TC_LOG_INFO("sql.driver", "Closing down DatabasePool '%s'.", GetDatabaseName()); + + //! Closes the actualy MySQL connection. + _connections[IDX_ASYNC].clear(); + + TC_LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '%s' terminated. " + "Proceeding with synchronous connections.", + GetDatabaseName()); + + //! Shut down the synchronous connections + //! There's no need for locking the connection, because DatabaseWorkerPool<>::Close + //! should only be called after any other thread tasks in the core have exited, + //! meaning there can be no concurrent access at this point. + _connections[IDX_SYNCH].clear(); + + TC_LOG_INFO("sql.driver", "All connections on DatabasePool '%s' closed.", GetDatabaseName()); +} + +template <class T> +bool DatabaseWorkerPool<T>::PrepareStatements() +{ + for (auto& connections : _connections) + for (auto& connection : connections) + { + connection->LockIfReady(); + if (!connection->PrepareStatements()) + { + connection->Unlock(); + Close(); + return false; + } + else + connection->Unlock(); + } + + return true; +} + +template <class T> +QueryResult DatabaseWorkerPool<T>::Query(const char* sql, T* connection /*= nullptr*/) +{ + if (!connection) + connection = GetFreeConnection(); + + ResultSet* result = connection->Query(sql); + connection->Unlock(); + if (!result || !result->GetRowCount() || !result->NextRow()) + { + delete result; + return QueryResult(NULL); + } + + return QueryResult(result); +} + +template <class T> +PreparedQueryResult DatabaseWorkerPool<T>::Query(PreparedStatement* stmt) +{ + auto connection = GetFreeConnection(); + PreparedResultSet* ret = connection->Query(stmt); + connection->Unlock(); + + //! Delete proxy-class. Not needed anymore + delete stmt; + + if (!ret || !ret->GetRowCount()) + { + delete ret; + return PreparedQueryResult(NULL); + } + + return PreparedQueryResult(ret); +} + +template <class T> +QueryResultFuture DatabaseWorkerPool<T>::AsyncQuery(const char* sql) +{ + BasicStatementTask* task = new BasicStatementTask(sql, true); + // Store future result before enqueueing - task might get already processed and deleted before returning from this method + QueryResultFuture result = task->GetFuture(); + Enqueue(task); + return result; +} + +template <class T> +PreparedQueryResultFuture DatabaseWorkerPool<T>::AsyncQuery(PreparedStatement* stmt) +{ + PreparedStatementTask* task = new PreparedStatementTask(stmt, true); + // Store future result before enqueueing - task might get already processed and deleted before returning from this method + PreparedQueryResultFuture result = task->GetFuture(); + Enqueue(task); + return result; +} + +template <class T> +QueryResultHolderFuture DatabaseWorkerPool<T>::DelayQueryHolder(SQLQueryHolder* holder) +{ + SQLQueryHolderTask* task = new SQLQueryHolderTask(holder); + // Store future result before enqueueing - task might get already processed and deleted before returning from this method + QueryResultHolderFuture result = task->GetFuture(); + Enqueue(task); + return result; +} + +template <class T> +void DatabaseWorkerPool<T>::CommitTransaction(SQLTransaction transaction) +{ +#ifdef TRINITY_DEBUG + //! Only analyze transaction weaknesses in Debug mode. + //! Ideally we catch the faults in Debug mode and then correct them, + //! so there's no need to waste these CPU cycles in Release mode. + switch (transaction->GetSize()) + { + case 0: + TC_LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing."); + return; + case 1: + TC_LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); + break; + default: + break; + } +#endif // TRINITY_DEBUG + + Enqueue(new TransactionTask(transaction)); +} + +template <class T> +void DatabaseWorkerPool<T>::DirectCommitTransaction(SQLTransaction& transaction) +{ + T* connection = GetFreeConnection(); + int errorCode = connection->ExecuteTransaction(transaction); + if (!errorCode) + { + connection->Unlock(); // OK, operation succesful + return; + } + + //! Handle MySQL Errno 1213 without extending deadlock to the core itself + /// @todo More elegant way + if (errorCode == ER_LOCK_DEADLOCK) + { + uint8 loopBreaker = 5; + for (uint8 i = 0; i < loopBreaker; ++i) + { + if (!connection->ExecuteTransaction(transaction)) + break; + } + } + + //! Clean up now. + transaction->Cleanup(); + + connection->Unlock(); +} + +template <class T> +void DatabaseWorkerPool<T>::EscapeString(std::string& str) +{ + if (str.empty()) + return; + + char* buf = new char[str.size() * 2 + 1]; + EscapeString(buf, str.c_str(), uint32(str.size())); + str = buf; + delete[] buf; +} + +template <class T> +void DatabaseWorkerPool<T>::KeepAlive() +{ + //! Ping synchronous connections + for (auto& connection : _connections[IDX_SYNCH]) + { + if (connection->LockIfReady()) + { + connection->Ping(); + connection->Unlock(); + } + } + + //! Assuming all worker threads are free, every worker thread will receive 1 ping operation request + //! If one or more worker threads are busy, the ping operations will not be split evenly, but this doesn't matter + //! as the sole purpose is to prevent connections from idling. + auto const count = _connections[IDX_ASYNC].size(); + for (uint8 i = 0; i < count; ++i) + Enqueue(new PingOperation); +} + +template <class T> +uint32 DatabaseWorkerPool<T>::OpenConnections(InternalIndex type, uint8 numConnections) +{ + for (uint8 i = 0; i < numConnections; ++i) + { + // Create the connection + auto connection = [&] { + switch (type) + { + case IDX_ASYNC: + return Trinity::make_unique<T>(_queue.get(), *_connectionInfo); + case IDX_SYNCH: + return Trinity::make_unique<T>(*_connectionInfo); + default: + ABORT(); + } + }(); + + if (uint32 error = connection->Open()) + { + // Failed to open a connection or invalid version, abort and cleanup + _connections[type].clear(); + return error; + } + else if (mysql_get_server_version(connection->GetHandle()) < MIN_MYSQL_SERVER_VERSION) + { + TC_LOG_ERROR("sql.driver", "TrinityCore does not support MySQL versions below 5.1"); + return 1; + } + else + { + _connections[type].push_back(std::move(connection)); + } + } + + // Everything is fine + return 0; +} + +template <class T> +T* DatabaseWorkerPool<T>::GetFreeConnection() +{ + uint8 i = 0; + auto const num_cons = _connections[IDX_SYNCH].size(); + T* connection = nullptr; + //! Block forever until a connection is free + for (;;) + { + connection = _connections[IDX_SYNCH][++i % num_cons].get(); + //! Must be matched with t->Unlock() or you will get deadlocks + if (connection->LockIfReady()) + break; + } + + return connection; +} + +template class TC_DATABASE_API DatabaseWorkerPool<LoginDatabaseConnection>; +template class TC_DATABASE_API DatabaseWorkerPool<WorldDatabaseConnection>; +template class TC_DATABASE_API DatabaseWorkerPool<CharacterDatabaseConnection>; diff --git a/src/server/database/Database/DatabaseWorkerPool.h b/src/server/database/Database/DatabaseWorkerPool.h index d5a254647eb..ffdde91c0a6 100644 --- a/src/server/database/Database/DatabaseWorkerPool.h +++ b/src/server/database/Database/DatabaseWorkerPool.h @@ -19,7 +19,7 @@ #define _DATABASEWORKERPOOL_H #include "Common.h" -#include "Callback.h" +#include "QueryCallback.h" #include "MySQLConnection.h" #include "Transaction.h" #include "DatabaseWorker.h" @@ -32,9 +32,7 @@ #include <mysqld_error.h> #include <memory> - -#define MIN_MYSQL_SERVER_VERSION 50100u -#define MIN_MYSQL_CLIENT_VERSION 50100u +#include <array> class PingOperation : public SQLOperation { @@ -59,97 +57,21 @@ class DatabaseWorkerPool public: /* Activity state */ - DatabaseWorkerPool() : _queue(new ProducerConsumerQueue<SQLOperation*>()), - _async_threads(0), _synch_threads(0) - { - memset(_connectionCount, 0, sizeof(_connectionCount)); - _connections.resize(IDX_SIZE); - - WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe."); - WPFatal(mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION, "TrinityCore does not support MySQL versions below 5.1"); - WPFatal(mysql_get_client_version() == MYSQL_VERSION_ID, "Used MySQL library version (%s) does not match the version used to compile TrinityCore (%s).", - mysql_get_client_info(), MYSQL_SERVER_VERSION); - } + DatabaseWorkerPool(); ~DatabaseWorkerPool() { _queue->Cancel(); } - void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads) - { - _connectionInfo.reset(new MySQLConnectionInfo(infoString)); - - _async_threads = asyncThreads; - _synch_threads = synchThreads; - } + void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads); - uint32 Open() - { - WPFatal(_connectionInfo.get(), "Connection info was not set!"); + uint32 Open(); - TC_LOG_INFO("sql.driver", "Opening DatabasePool '%s'. Asynchronous connections: %u, synchronous connections: %u.", - GetDatabaseName(), _async_threads, _synch_threads); - - uint32 error = OpenConnections(IDX_ASYNC, _async_threads); - - if (error) - return error; - - error = OpenConnections(IDX_SYNCH, _synch_threads); - - if (!error) - { - TC_LOG_INFO("sql.driver", "DatabasePool '%s' opened successfully. %u total connections running.", GetDatabaseName(), - (_connectionCount[IDX_SYNCH] + _connectionCount[IDX_ASYNC])); - } - - return error; - } - - void Close() - { - TC_LOG_INFO("sql.driver", "Closing down DatabasePool '%s'.", GetDatabaseName()); - - for (uint8 i = 0; i < _connectionCount[IDX_ASYNC]; ++i) - { - T* t = _connections[IDX_ASYNC][i]; - t->Close(); //! Closes the actualy MySQL connection. - } - - TC_LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '%s' terminated. Proceeding with synchronous connections.", - GetDatabaseName()); - - //! Shut down the synchronous connections - //! There's no need for locking the connection, because DatabaseWorkerPool<>::Close - //! should only be called after any other thread tasks in the core have exited, - //! meaning there can be no concurrent access at this point. - for (uint8 i = 0; i < _connectionCount[IDX_SYNCH]; ++i) - _connections[IDX_SYNCH][i]->Close(); - - TC_LOG_INFO("sql.driver", "All connections on DatabasePool '%s' closed.", GetDatabaseName()); - } + void Close(); //! Prepares all prepared statements - bool PrepareStatements() - { - for (uint8 i = 0; i < IDX_SIZE; ++i) - for (uint32 c = 0; c < _connectionCount[i]; ++c) - { - T* t = _connections[i][c]; - t->LockIfReady(); - if (!t->PrepareStatements()) - { - t->Unlock(); - Close(); - return false; - } - else - t->Unlock(); - } - - return true; - } + bool PrepareStatements(); inline MySQLConnectionInfo const* GetConnectionInfo() const { @@ -198,12 +120,12 @@ class DatabaseWorkerPool //! This method should only be used for queries that are only executed once, e.g during startup. void DirectExecute(const char* sql) { - if (!sql) + if (Trinity::IsFormatEmptyOrNull(sql)) return; - T* t = GetFreeConnection(); - t->Execute(sql); - t->Unlock(); + T* connection = GetFreeConnection(); + connection->Execute(sql); + connection->Unlock(); } //! Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished. @@ -221,9 +143,9 @@ class DatabaseWorkerPool //! Statement must be prepared with the CONNECTION_SYNCH flag. void DirectExecute(PreparedStatement* stmt) { - T* t = GetFreeConnection(); - t->Execute(stmt); - t->Unlock(); + T* connection = GetFreeConnection(); + connection->Execute(stmt); + connection->Unlock(); //! Delete proxy-class. Not needed anymore delete stmt; @@ -235,21 +157,7 @@ class DatabaseWorkerPool //! Directly executes an SQL query in string format that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. - QueryResult Query(const char* sql, T* conn = nullptr) - { - if (!conn) - conn = GetFreeConnection(); - - ResultSet* result = conn->Query(sql); - conn->Unlock(); - if (!result || !result->GetRowCount() || !result->NextRow()) - { - delete result; - return QueryResult(NULL); - } - - return QueryResult(result); - } + QueryResult Query(const char* sql, T* connection = nullptr); //! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. @@ -267,7 +175,7 @@ class DatabaseWorkerPool template<typename Format, typename... Args> QueryResult PQuery(Format&& sql, Args&&... args) { - if (!sql) + if (Trinity::IsFormatEmptyOrNull(sql)) return QueryResult(nullptr); return Query(Trinity::StringFormat(std::forward<Format>(sql), std::forward<Args>(args)...).c_str()); @@ -276,23 +184,7 @@ class DatabaseWorkerPool //! Directly executes an SQL query in prepared format that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. //! Statement must be prepared with CONNECTION_SYNCH flag. - PreparedQueryResult Query(PreparedStatement* stmt) - { - T* t = GetFreeConnection(); - PreparedResultSet* ret = t->Query(stmt); - t->Unlock(); - - //! Delete proxy-class. Not needed anymore - delete stmt; - - if (!ret || !ret->GetRowCount()) - { - delete ret; - return PreparedQueryResult(NULL); - } - - return PreparedQueryResult(ret); - } + PreparedQueryResult Query(PreparedStatement* stmt); /** Asynchronous query (with resultset) methods. @@ -300,14 +192,7 @@ class DatabaseWorkerPool //! Enqueues a query in string format that will set the value of the QueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. - QueryResultFuture AsyncQuery(const char* sql) - { - BasicStatementTask* task = new BasicStatementTask(sql, true); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - QueryResultFuture result = task->GetFuture(); - Enqueue(task); - return result; - } + QueryResultFuture AsyncQuery(const char* sql); //! Enqueues a query in string format -with variable args- that will set the value of the QueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. @@ -320,27 +205,13 @@ class DatabaseWorkerPool //! Enqueues a query in prepared format that will set the value of the PreparedQueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. //! Statement must be prepared with CONNECTION_ASYNC flag. - PreparedQueryResultFuture AsyncQuery(PreparedStatement* stmt) - { - PreparedStatementTask* task = new PreparedStatementTask(stmt, true); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - PreparedQueryResultFuture result = task->GetFuture(); - Enqueue(task); - return result; - } + PreparedQueryResultFuture AsyncQuery(PreparedStatement* stmt); //! Enqueues a vector of SQL operations (can be both adhoc and prepared) that will set the value of the QueryResultHolderFuture //! return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. //! Any prepared statements added to this holder need to be prepared with the CONNECTION_ASYNC flag. - QueryResultHolderFuture DelayQueryHolder(SQLQueryHolder* holder) - { - SQLQueryHolderTask* task = new SQLQueryHolderTask(holder); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - QueryResultHolderFuture result = task->GetFuture(); - Enqueue(task); - return result; - } + QueryResultHolderFuture DelayQueryHolder(SQLQueryHolder* holder); /** Transaction context methods. @@ -354,57 +225,11 @@ class DatabaseWorkerPool //! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. - void CommitTransaction(SQLTransaction transaction) - { - #ifdef TRINITY_DEBUG - //! Only analyze transaction weaknesses in Debug mode. - //! Ideally we catch the faults in Debug mode and then correct them, - //! so there's no need to waste these CPU cycles in Release mode. - switch (transaction->GetSize()) - { - case 0: - TC_LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing."); - return; - case 1: - TC_LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); - break; - default: - break; - } - #endif // TRINITY_DEBUG - - Enqueue(new TransactionTask(transaction)); - } + void CommitTransaction(SQLTransaction transaction); //! Directly executes a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. - void DirectCommitTransaction(SQLTransaction& transaction) - { - T* con = GetFreeConnection(); - int errorCode = con->ExecuteTransaction(transaction); - if (!errorCode) - { - con->Unlock(); // OK, operation succesful - return; - } - - //! Handle MySQL Errno 1213 without extending deadlock to the core itself - /// @todo More elegant way - if (errorCode == ER_LOCK_DEADLOCK) - { - uint8 loopBreaker = 5; - for (uint8 i = 0; i < loopBreaker; ++i) - { - if (!con->ExecuteTransaction(transaction)) - break; - } - } - - //! Clean up now. - transaction->Cleanup(); - - con->Unlock(); - } + void DirectCommitTransaction(SQLTransaction& transaction); //! Method used to execute prepared statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. @@ -441,90 +266,21 @@ class DatabaseWorkerPool } //! Apply escape string'ing for current collation. (utf8) - void EscapeString(std::string& str) - { - if (str.empty()) - return; - - char* buf = new char[str.size() * 2 + 1]; - EscapeString(buf, str.c_str(), str.size()); - str = buf; - delete[] buf; - } + void EscapeString(std::string& str); //! Keeps all our MySQL connections alive, prevent the server from disconnecting us. - void KeepAlive() - { - //! Ping synchronous connections - for (uint8 i = 0; i < _connectionCount[IDX_SYNCH]; ++i) - { - T* t = _connections[IDX_SYNCH][i]; - if (t->LockIfReady()) - { - t->Ping(); - t->Unlock(); - } - } - - //! Assuming all worker threads are free, every worker thread will receive 1 ping operation request - //! If one or more worker threads are busy, the ping operations will not be split evenly, but this doesn't matter - //! as the sole purpose is to prevent connections from idling. - for (size_t i = 0; i < _connections[IDX_ASYNC].size(); ++i) - Enqueue(new PingOperation); - } + void KeepAlive(); private: - uint32 OpenConnections(InternalIndex type, uint8 numConnections) - { - _connections[type].resize(numConnections); - for (uint8 i = 0; i < numConnections; ++i) - { - T* t; - - if (type == IDX_ASYNC) - t = new T(_queue.get(), *_connectionInfo); - else if (type == IDX_SYNCH) - t = new T(*_connectionInfo); - else - ABORT(); - - _connections[type][i] = t; - ++_connectionCount[type]; - - uint32 error = t->Open(); - - if (!error) - { - if (mysql_get_server_version(t->GetHandle()) < MIN_MYSQL_SERVER_VERSION) - { - TC_LOG_ERROR("sql.driver", "TrinityCore does not support MySQL versions below 5.1"); - error = 1; - } - } - - // Failed to open a connection or invalid version, abort and cleanup - if (error) - { - while (_connectionCount[type] != 0) - { - t = _connections[type][i--]; - delete t; - --_connectionCount[type]; - } - return error; - } - } - - // Everything is fine - return 0; - } + uint32 OpenConnections(InternalIndex type, uint8 numConnections); unsigned long EscapeString(char *to, const char *from, unsigned long length) { if (!to || !from || !length) return 0; - return mysql_real_escape_string(_connections[IDX_SYNCH][0]->GetHandle(), to, from, length); + return mysql_real_escape_string( + _connections[IDX_SYNCH].front()->GetHandle(), to, from, length); } void Enqueue(SQLOperation* op) @@ -534,22 +290,7 @@ class DatabaseWorkerPool //! Gets a free connection in the synchronous connection pool. //! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks. - T* GetFreeConnection() - { - uint8 i = 0; - size_t num_cons = _connectionCount[IDX_SYNCH]; - T* t = NULL; - //! Block forever until a connection is free - for (;;) - { - t = _connections[IDX_SYNCH][++i % num_cons]; - //! Must be matched with t->Unlock() or you will get deadlocks - if (t->LockIfReady()) - break; - } - - return t; - } + T* GetFreeConnection(); char const* GetDatabaseName() const { @@ -558,9 +299,7 @@ class DatabaseWorkerPool //! Queue shared by async worker threads. std::unique_ptr<ProducerConsumerQueue<SQLOperation*>> _queue; - std::vector<std::vector<T*>> _connections; - //! Counter of MySQL connections; - uint32 _connectionCount[IDX_SIZE]; + std::array<std::vector<std::unique_ptr<T>>, IDX_SIZE> _connections; std::unique_ptr<MySQLConnectionInfo> _connectionInfo; uint8 _async_threads, _synch_threads; }; diff --git a/src/server/database/Database/Field.h b/src/server/database/Database/Field.h index ec9e626ee1b..123e25dbbf3 100644 --- a/src/server/database/Database/Field.h +++ b/src/server/database/Database/Field.h @@ -53,7 +53,7 @@ | SUM, AVG | DECIMAL | | COUNT | BIGINT | */ -class Field +class TC_DATABASE_API Field { friend class ResultSet; friend class PreparedResultSet; @@ -323,7 +323,7 @@ class Field data.value = NULL; } - static size_t SizeForType(MYSQL_FIELD* field) + static uint32 SizeForType(MYSQL_FIELD* field) { switch (field->type) { diff --git a/src/server/database/Database/Implementation/CharacterDatabase.cpp b/src/server/database/Database/Implementation/CharacterDatabase.cpp index ab68aca2a8c..bb0e2bb09d4 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.cpp +++ b/src/server/database/Database/Implementation/CharacterDatabase.cpp @@ -42,11 +42,11 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_SEL_MAIL_LIST_INFO, "SELECT id, sender, (SELECT name FROM characters WHERE guid = sender) AS sendername, receiver, (SELECT name FROM characters WHERE guid = receiver) AS receivername, " "subject, deliver_time, expire_time, money, has_items FROM mail WHERE receiver = ? ", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_MAIL_LIST_ITEMS, "SELECT itemEntry,count FROM item_instance WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_ENUM, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.playerBytes, c.playerBytes2, c.level, c.zone, c.map, c.position_x, c.position_y, c.position_z, " + PrepareStatement(CHAR_SEL_ENUM, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.skin, c.face, c.hairStyle, c.hairColor, c.facialStyle, c.level, c.zone, c.map, c.position_x, c.position_y, c.position_z, " "gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, cb.guid " "FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? LEFT JOIN guild_member AS gm ON c.guid = gm.guid " "LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ? AND c.deleteInfos_Name IS NULL ORDER BY c.guid", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_ENUM_DECLINED_NAME, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.playerBytes, c.playerBytes2, c.level, c.zone, c.map, " + PrepareStatement(CHAR_SEL_ENUM_DECLINED_NAME, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.skin, c.face, c.hairStyle, c.hairColor, c.facialStyle, c.level, c.zone, c.map, " "c.position_x, c.position_y, c.position_z, gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, " "cb.guid, cd.genitive FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? " "LEFT JOIN character_declinedname AS cd ON c.guid = cd.guid LEFT JOIN guild_member AS gm ON c.guid = gm.guid " @@ -56,7 +56,7 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_SEL_CHAR_RACE, "SELECT race FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHAR_LEVEL, "SELECT level FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHAR_ZONE, "SELECT zone FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_NAME_DATA, "SELECT race, class, gender, level FROM characters WHERE guid = ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_CHARACTER_NAME_DATA, "SELECT race, class, gender, level, name FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHAR_POSITION_XYZ, "SELECT map, position_x, position_y, position_z FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHAR_POSITION, "SELECT position_x, position_y, position_z, orientation, map, taxi_path FROM characters WHERE guid = ?", CONNECTION_SYNCH); @@ -64,7 +64,7 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_DEL_BATTLEGROUND_RANDOM, "DELETE FROM character_battleground_random WHERE guid = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_INS_BATTLEGROUND_RANDOM, "INSERT INTO character_battleground_random (guid) VALUES (?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER, "SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, " + PrepareStatement(CHAR_SEL_CHARACTER, "SELECT guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " "position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, " "resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, " "arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, " @@ -157,11 +157,9 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_DEL_GIFT, "DELETE FROM character_gifts WHERE item_guid = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM, "SELECT entry, flags FROM character_gifts WHERE item_guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_ACCOUNT_BY_NAME, "SELECT account FROM characters WHERE name = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_DATA_BY_GUID, "SELECT account, name, level FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES, "DELETE FROM account_instance_times WHERE accountId = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES, "INSERT INTO account_instance_times (accountId, instanceId, releaseTime) VALUES (?, ?, ?)", CONNECTION_ASYNC); PrepareStatement(CHAR_SEL_CHARACTER_NAME_CLASS, "SELECT name, class FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_NAME, "SELECT name FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_MATCH_MAKER_RATING, "SELECT matchMakerRating FROM character_arena_stats WHERE guid = ? AND slot = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHARACTER_COUNT, "SELECT account, COUNT(guid) FROM characters WHERE account = ? GROUP BY account", CONNECTION_ASYNC); PrepareStatement(CHAR_UPD_NAME, "UPDATE characters set name = ?, at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC); @@ -351,7 +349,7 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_DEL_LFG_DATA, "DELETE FROM lfg_data WHERE guid = ?", CONNECTION_ASYNC); // Player saving - PrepareStatement(CHAR_INS_CHARACTER, "INSERT INTO characters (guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, " + PrepareStatement(CHAR_INS_CHARACTER, "INSERT INTO characters (guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " "map, instance_id, instance_mode_mask, position_x, position_y, position_z, orientation, trans_x, trans_y, trans_z, trans_o, transguid, " "taximask, cinematic, " "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, " @@ -359,8 +357,8 @@ void CharacterDatabaseConnection::DoPrepareStatements() "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, " "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, " "power4, power5, power6, power7, latency, talentGroupsCount, activeTalentGroup, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels) VALUES " - "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHARACTER, "UPDATE characters SET name=?,race=?,class=?,gender=?,level=?,xp=?,money=?,playerBytes=?,playerBytes2=?,playerFlags=?," + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_UPD_CHARACTER, "UPDATE characters SET name=?,race=?,class=?,gender=?,level=?,xp=?,money=?,skin=?,face=?,hairStyle=?,hairColor=?,facialStyle=?,bankSlots=?,restState=?,playerFlags=?," "map=?,instance_id=?,instance_mode_mask=?,position_x=?,position_y=?,position_z=?,orientation=?,trans_x=?,trans_y=?,trans_z=?,trans_o=?,transguid=?,taximask=?,cinematic=?,totaltime=?,leveltime=?,rest_bonus=?," "logout_time=?,is_logout_resting=?,resettalents_cost=?,resettalents_time=?,extra_flags=?,stable_slots=?,at_login=?,zone=?,death_expire_time=?,taxi_path=?," "arenaPoints=?,totalHonorPoints=?,todayHonorPoints=?,yesterdayHonorPoints=?,totalKills=?,todayKills=?,yesterdayKills=?,chosenTitle=?,knownCurrencies=?," @@ -407,7 +405,7 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID, "DELETE FROM character_instance WHERE guid = ? AND instance = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_UPD_CHAR_INSTANCE, "UPDATE character_instance SET instance = ?, permanent = ?, extendState = ? WHERE guid = ? AND instance = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_INS_CHAR_INSTANCE, "INSERT INTO character_instance (guid, instance, permanent, extendState) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GENDER_PLAYERBYTES, "UPDATE characters SET gender = ?, playerBytes = ?, playerBytes2 = ? WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_UPD_GENDER_AND_APPEARANCE, "UPDATE characters SET gender = ?, skin = ?, face = ?, hairStyle = ?, hairColor = ?, facialStyle = ? WHERE guid = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_DEL_CHARACTER_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags | ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags & ~ ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); @@ -440,7 +438,6 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_SEL_CHAR_OLD_CHARS, "SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID, "SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid = ? AND type = ? LIMIT 1", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_MAIL, "SELECT id, messageType, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked, stationery, mailTemplateId FROM mail WHERE receiver = ? ORDER BY id DESC", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_PLAYERBYTES2, "SELECT playerBytes2 FROM characters WHERE guid = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_SEL_CHAR_GUID_BY_NAME, "SELECT guid FROM characters WHERE name = ?", CONNECTION_SYNCH); PrepareStatement(CHAR_DEL_CHAR_AURA_FROZEN, "DELETE FROM character_aura WHERE spell = 9454 AND guid = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE itemEntry = ?", CONNECTION_SYNCH); diff --git a/src/server/database/Database/Implementation/CharacterDatabase.h b/src/server/database/Database/Implementation/CharacterDatabase.h index 19d4a609e77..0cac6d35b55 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.h +++ b/src/server/database/Database/Implementation/CharacterDatabase.h @@ -146,13 +146,11 @@ enum CharacterDatabaseStatements CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES, CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES, CHAR_SEL_CHARACTER_NAME_CLASS, - CHAR_SEL_CHARACTER_NAME, CHAR_SEL_MATCH_MAKER_RATING, CHAR_SEL_CHARACTER_COUNT, CHAR_UPD_NAME, CHAR_UPD_NAME_BY_GUID, CHAR_DEL_DECLINED_NAME, - CHAR_SEL_CHARACTER_DATA_BY_GUID, CHAR_INS_GUILD, CHAR_DEL_GUILD, @@ -334,7 +332,7 @@ enum CharacterDatabaseStatements CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID, CHAR_UPD_CHAR_INSTANCE, CHAR_INS_CHAR_INSTANCE, - CHAR_UPD_GENDER_PLAYERBYTES, + CHAR_UPD_GENDER_AND_APPEARANCE, CHAR_DEL_CHARACTER_SKILL, CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS, CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS, @@ -371,7 +369,6 @@ enum CharacterDatabaseStatements CHAR_SEL_CHAR_OLD_CHARS, CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID, CHAR_SEL_MAIL, - CHAR_SEL_CHAR_PLAYERBYTES2, CHAR_SEL_CHAR_GUID_BY_NAME, CHAR_DEL_CHAR_AURA_FROZEN, CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM, @@ -538,7 +535,7 @@ enum CharacterDatabaseStatements MAX_CHARACTERDATABASE_STATEMENTS }; -class CharacterDatabaseConnection : public MySQLConnection +class TC_DATABASE_API CharacterDatabaseConnection : public MySQLConnection { public: typedef CharacterDatabaseStatements Statements; diff --git a/src/server/database/Database/Implementation/LoginDatabase.cpp b/src/server/database/Database/Implementation/LoginDatabase.cpp index 66847f0a6a0..4f056e2686d 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.cpp +++ b/src/server/database/Database/Implementation/LoginDatabase.cpp @@ -24,33 +24,34 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_SEL_REALMLIST, "SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE flag <> 3 ORDER BY name", CONNECTION_SYNCH); PrepareStatement(LOGIN_DEL_EXPIRED_IP_BANS, "DELETE FROM ip_banned WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_SYNCH); + PrepareStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_IP_INFO, "(SELECT unbandate > UNIX_TIMESTAMP() OR unbandate = bandate AS banned, NULL as country FROM ip_banned WHERE ip = ?) " "UNION " "(SELECT NULL AS banned, country FROM ip2nation WHERE INET_NTOA(ip) = ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_IP_BANNED, "SELECT * FROM ip_banned WHERE ip = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_INS_IP_AUTO_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Trinity Auth', 'Failed login autoban')", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_IP_BANNED_ALL, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) ORDER BY unbandate", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_IP_BANNED_BY_IP, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) AND ip LIKE CONCAT('%%', ?, '%%') ORDER BY unbandate", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED, "SELECT bandate, unbandate FROM account_banned WHERE id = ? AND active = 1", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 AND username LIKE CONCAT('%%', ?, '%%') GROUP BY account.id", CONNECTION_SYNCH); PrepareStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Trinity Auth', 'Failed login autoban', 1)", CONNECTION_ASYNC); PrepareStatement(LOGIN_DEL_ACCOUNT_BANNED, "DELETE FROM account_banned WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_SESSIONKEY, "SELECT a.sessionkey, a.id, aa.gmlevel FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE username = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_UPD_VS, "UPDATE account SET v = ?, s = ? WHERE username = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_LOGONPROOF, "UPDATE account SET sessionkey = ?, last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_LOGONCHALLENGE, "SELECT a.sha_pass_hash, a.id, a.locked, a.lock_country, a.last_ip, aa.gmlevel, a.v, a.s, a.token_key FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH); + PrepareStatement(LOGIN_SEL_LOGONCHALLENGE, "SELECT a.id, a.username, a.locked, a.lock_country, a.last_ip, a.failed_logins, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, " + "ab.unbandate = ab.bandate, aa.gmlevel, a.token_key, a.sha_pass_hash, a.v, a.s " + "FROM account a LEFT JOIN account_access aa ON a.id = aa.id LEFT JOIN account_banned ab ON ab.id = a.id AND ab.active = 1 WHERE a.username = ?", CONNECTION_ASYNC); + PrepareStatement(LOGIN_SEL_RECONNECTCHALLENGE, "SELECT a.id, UPPER(a.username), a.locked, a.lock_country, a.last_ip, a.failed_logins, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, " + "ab.unbandate = ab.bandate, aa.gmlevel, a.sessionKey " + "FROM account a LEFT JOIN account_access aa ON a.id = aa.id LEFT JOIN account_banned ab ON ab.id = a.id AND ab.active = 1 WHERE a.username = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_LOGON_COUNTRY, "SELECT country FROM ip2nation WHERE ip < ? ORDER BY ip DESC LIMIT 0,1", CONNECTION_SYNCH); PrepareStatement(LOGIN_UPD_FAILEDLOGINS, "UPDATE account SET failed_logins = failed_logins + 1 WHERE username = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_FAILEDLOGINS, "SELECT id, failed_logins FROM account WHERE username = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_ID_BY_NAME, "SELECT id FROM account WHERE username = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME, "SELECT id, username FROM account WHERE username = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME, "SELECT a.id, a.sessionkey, a.last_ip, a.locked, a.lock_country, a.expansion, a.mutetime, a.locale, a.recruiter, a.os, aa.gmLevel, " "ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, r.id FROM account a LEFT JOIN account_access aa ON a.id = aa.id AND aa.RealmID IN (-1, ?) " "LEFT JOIN account_banned ab ON a.id = ab.id AND ab.active = 1 LEFT JOIN account r ON a.id = r.recruiter WHERE a.username = ? ORDER BY aa.RealmID DESC LIMIT 1", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL, "SELECT id, username FROM account WHERE email = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_NUM_CHARS_ON_REALM, "SELECT numchars FROM realmcharacters WHERE realmid = ? AND acctid= ?", CONNECTION_SYNCH); + PrepareStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS, "SELECT realmid, numchars FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_ACCOUNT_BY_IP, "SELECT id, username FROM account WHERE last_ip = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_BY_ID, "SELECT 1 FROM account WHERE id = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_INS_IP_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?)", CONNECTION_ASYNC); diff --git a/src/server/database/Database/Implementation/LoginDatabase.h b/src/server/database/Database/Implementation/LoginDatabase.h index 69c2e758551..e206be16d73 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.h +++ b/src/server/database/Database/Implementation/LoginDatabase.h @@ -33,25 +33,22 @@ enum LoginDatabaseStatements LOGIN_DEL_EXPIRED_IP_BANS, LOGIN_UPD_EXPIRED_ACCOUNT_BANS, LOGIN_SEL_IP_INFO, - LOGIN_SEL_IP_BANNED, LOGIN_INS_IP_AUTO_BANNED, - LOGIN_SEL_ACCOUNT_BANNED, LOGIN_SEL_ACCOUNT_BANNED_ALL, LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME, LOGIN_INS_ACCOUNT_AUTO_BANNED, LOGIN_DEL_ACCOUNT_BANNED, - LOGIN_SEL_SESSIONKEY, LOGIN_UPD_VS, LOGIN_UPD_LOGONPROOF, LOGIN_SEL_LOGONCHALLENGE, + LOGIN_SEL_RECONNECTCHALLENGE, LOGIN_SEL_LOGON_COUNTRY, LOGIN_UPD_FAILEDLOGINS, - LOGIN_SEL_FAILEDLOGINS, LOGIN_SEL_ACCOUNT_ID_BY_NAME, LOGIN_SEL_ACCOUNT_LIST_BY_NAME, LOGIN_SEL_ACCOUNT_INFO_BY_NAME, LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL, - LOGIN_SEL_NUM_CHARS_ON_REALM, + LOGIN_SEL_REALM_CHARACTER_COUNTS, LOGIN_SEL_ACCOUNT_BY_IP, LOGIN_INS_IP_BANNED, LOGIN_DEL_IP_NOT_BANNED, @@ -119,7 +116,7 @@ enum LoginDatabaseStatements MAX_LOGINDATABASE_STATEMENTS }; -class LoginDatabaseConnection : public MySQLConnection +class TC_DATABASE_API LoginDatabaseConnection : public MySQLConnection { public: typedef LoginDatabaseStatements Statements; diff --git a/src/server/database/Database/Implementation/WorldDatabase.cpp b/src/server/database/Database/Implementation/WorldDatabase.cpp index 7a183d5bf78..83720c1a996 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.cpp +++ b/src/server/database/Database/Implementation/WorldDatabase.cpp @@ -30,8 +30,8 @@ void WorldDatabaseConnection::DoPrepareStatements() PrepareStatement(WORLD_SEL_SMARTAI_WP, "SELECT entry, pointid, position_x, position_y, position_z FROM waypoints ORDER BY entry, pointid", CONNECTION_SYNCH); PrepareStatement(WORLD_DEL_GAMEOBJECT, "DELETE FROM gameobject WHERE guid = ?", CONNECTION_ASYNC); PrepareStatement(WORLD_DEL_EVENT_GAMEOBJECT, "DELETE FROM game_event_gameobject WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_GRAVEYARD_ZONE, "INSERT INTO game_graveyard_zone (id, ghost_zone, faction) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_GRAVEYARD_ZONE, "DELETE FROM game_graveyard_zone WHERE id = ? AND ghost_zone = ? AND faction = ?", CONNECTION_ASYNC); + PrepareStatement(WORLD_INS_GRAVEYARD_ZONE, "INSERT INTO graveyard_zone (ID, GhostZone, Faction) VALUES (?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(WORLD_DEL_GRAVEYARD_ZONE, "DELETE FROM graveyard_zone WHERE ID = ? AND GhostZone = ? AND Faction = ?", CONNECTION_ASYNC); PrepareStatement(WORLD_INS_GAME_TELE, "INSERT INTO game_tele (id, position_x, position_y, position_z, orientation, map, name) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); PrepareStatement(WORLD_DEL_GAME_TELE, "DELETE FROM game_tele WHERE name = ?", CONNECTION_ASYNC); PrepareStatement(WORLD_INS_NPC_VENDOR, "INSERT INTO npc_vendor (entry, item, maxcount, incrtime, extendedcost) VALUES(?, ?, ?, ?, ?)", CONNECTION_ASYNC); diff --git a/src/server/database/Database/Implementation/WorldDatabase.h b/src/server/database/Database/Implementation/WorldDatabase.h index 6ac4ce589e3..e0a02423446 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.h +++ b/src/server/database/Database/Implementation/WorldDatabase.h @@ -103,7 +103,7 @@ enum WorldDatabaseStatements MAX_WORLDDATABASE_STATEMENTS }; -class WorldDatabaseConnection : public MySQLConnection +class TC_DATABASE_API WorldDatabaseConnection : public MySQLConnection { public: typedef WorldDatabaseStatements Statements; diff --git a/src/server/database/Database/MySQLConnection.cpp b/src/server/database/Database/MySQLConnection.cpp index 41dd61d3c3a..93d2a35f310 100644 --- a/src/server/database/Database/MySQLConnection.cpp +++ b/src/server/database/Database/MySQLConnection.cpp @@ -37,7 +37,6 @@ MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo) : m_reconnecting(false), m_prepareError(false), m_queue(NULL), -m_worker(NULL), m_Mysql(NULL), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_SYNCH) { } @@ -50,24 +49,26 @@ m_Mysql(NULL), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_ASYNC) { - m_worker = new DatabaseWorker(m_queue, this); + m_worker = Trinity::make_unique<DatabaseWorker>(m_queue, this); } MySQLConnection::~MySQLConnection() { - delete m_worker; - - for (size_t i = 0; i < m_stmts.size(); ++i) - delete m_stmts[i]; - - if (m_Mysql) - mysql_close(m_Mysql); + Close(); } void MySQLConnection::Close() { - /// Only close us if we're not operating - delete this; + // Stop the worker thread before the statements are cleared + m_worker.reset(); + + m_stmts.clear(); + + if (m_Mysql) + { + mysql_close(m_Mysql); + m_Mysql = nullptr; + } } uint32 MySQLConnection::Open() @@ -412,7 +413,7 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index) { ASSERT(index < m_stmts.size()); - MySQLPreparedStatement* ret = m_stmts[index]; + MySQLPreparedStatement* ret = m_stmts[index].get(); if (!ret) TC_LOG_ERROR("sql.sql", "Could not fetch prepared statement %u on database `%s`, connection type: %s.", index, m_connectionInfo.database.c_str(), (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); @@ -424,16 +425,12 @@ void MySQLConnection::PrepareStatement(uint32 index, const char* sql, Connection { m_queries.insert(PreparedStatementMap::value_type(index, std::make_pair(sql, flags))); - // For reconnection case - if (m_reconnecting) - delete m_stmts[index]; - // Check if specified query should be prepared on this connection // i.e. don't prepare async statements on synchronous connections // to save memory that will not be used. if (!(m_connectionFlags & flags)) { - m_stmts[index] = NULL; + m_stmts[index].reset(); return; } @@ -455,8 +452,7 @@ void MySQLConnection::PrepareStatement(uint32 index, const char* sql, Connection } else { - MySQLPreparedStatement* mStmt = new MySQLPreparedStatement(stmt); - m_stmts[index] = mStmt; + m_stmts[index] = Trinity::make_unique<MySQLPreparedStatement>(stmt); } } } @@ -477,7 +473,7 @@ PreparedResultSet* MySQLConnection::Query(PreparedStatement* stmt) return new PreparedResultSet(stmt->m_stmt->GetSTMT(), result, rowCount, fieldCount); } -bool MySQLConnection::_HandleMySQLErrno(uint32 errNo) +bool MySQLConnection::_HandleMySQLErrno(uint32 errNo, uint8 attempts /*= 5*/) { switch (errNo) { @@ -486,9 +482,21 @@ bool MySQLConnection::_HandleMySQLErrno(uint32 errNo) case CR_INVALID_CONN_HANDLE: case CR_SERVER_LOST_EXTENDED: { + if (m_Mysql) + { + TC_LOG_ERROR("sql.sql", "Lost the connection to the MySQL server!"); + + mysql_close(GetHandle()); + m_Mysql = nullptr; + } + + /*no break*/ + } + case CR_CONN_HOST_ERROR: + { + TC_LOG_INFO("sql.sql", "Attempting to reconnect to the MySQL server..."); + m_reconnecting = true; - uint64 oldThreadId = mysql_thread_id(GetHandle()); - mysql_close(GetHandle()); uint32 const lErrno = Open(); if (!lErrno) @@ -496,24 +504,37 @@ bool MySQLConnection::_HandleMySQLErrno(uint32 errNo) // Don't remove 'this' pointer unless you want to skip loading all prepared statements... if (!this->PrepareStatements()) { - TC_LOG_ERROR("sql.sql", "Could not re-prepare statements!"); - Close(); - return false; + TC_LOG_FATAL("sql.sql", "Could not re-prepare statements!"); + std::this_thread::sleep_for(std::chrono::seconds(10)); + std::abort(); } - TC_LOG_INFO("sql.sql", "Connection to the MySQL server is active."); - if (oldThreadId != mysql_thread_id(GetHandle())) - TC_LOG_INFO("sql.sql", "Successfully reconnected to %s @%s:%s (%s).", - m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(), - (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); + TC_LOG_INFO("sql.sql", "Successfully reconnected to %s @%s:%s (%s).", + m_connectionInfo.database.c_str(), m_connectionInfo.host.c_str(), m_connectionInfo.port_or_socket.c_str(), + (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); m_reconnecting = false; return true; } - // It's possible this attempted reconnect throws 2006 at us. To prevent crazy recursive calls, sleep here. - std::this_thread::sleep_for(std::chrono::seconds(3)); // Sleep 3 seconds - return _HandleMySQLErrno(lErrno); // Call self (recursive) + if ((--attempts) == 0) + { + // Shut down the server when the mysql server isn't + // reachable for some time + TC_LOG_FATAL("sql.sql", "Failed to reconnect to the MySQL server, " + "terminating the server to prevent data corruption!"); + + // We could also initiate a shutdown through using std::raise(SIGTERM) + std::this_thread::sleep_for(std::chrono::seconds(10)); + std::abort(); + } + else + { + // It's possible this attempted reconnect throws 2006 at us. + // To prevent crazy recursive calls, sleep here. + std::this_thread::sleep_for(std::chrono::seconds(3)); // Sleep 3 seconds + return _HandleMySQLErrno(lErrno, attempts); // Call self (recursive) + } } case ER_LOCK_DEADLOCK: diff --git a/src/server/database/Database/MySQLConnection.h b/src/server/database/Database/MySQLConnection.h index a981caa607e..566995988c0 100644 --- a/src/server/database/Database/MySQLConnection.h +++ b/src/server/database/Database/MySQLConnection.h @@ -35,7 +35,7 @@ enum ConnectionFlags CONNECTION_BOTH = CONNECTION_ASYNC | CONNECTION_SYNCH }; -struct MySQLConnectionInfo +struct TC_DATABASE_API MySQLConnectionInfo { explicit MySQLConnectionInfo(std::string const& infoString) { @@ -62,7 +62,7 @@ struct MySQLConnectionInfo typedef std::map<uint32 /*index*/, std::pair<std::string /*query*/, ConnectionFlags /*sync/async*/> > PreparedStatementMap; -class MySQLConnection +class TC_DATABASE_API MySQLConnection { template <class T> friend class DatabaseWorkerPool; friend class PingOperation; @@ -116,18 +116,18 @@ class MySQLConnection virtual void DoPrepareStatements() = 0; protected: - std::vector<MySQLPreparedStatement*> m_stmts; //! PreparedStatements storage + std::vector<std::unique_ptr<MySQLPreparedStatement>> m_stmts; //! PreparedStatements storage PreparedStatementMap m_queries; //! Query storage bool m_reconnecting; //! Are we reconnecting? bool m_prepareError; //! Was there any error while preparing statements? private: - bool _HandleMySQLErrno(uint32 errNo); + bool _HandleMySQLErrno(uint32 errNo, uint8 attempts = 5); private: ProducerConsumerQueue<SQLOperation*>* m_queue; //! Queue shared with other asynchronous connections. - DatabaseWorker* m_worker; //! Core worker task. - MYSQL * m_Mysql; //! MySQL Handle. + std::unique_ptr<DatabaseWorker> m_worker; //! Core worker task. + MYSQL* m_Mysql; //! MySQL Handle. MySQLConnectionInfo& m_connectionInfo; //! Connection info (used for logging) ConnectionFlags m_connectionFlags; //! Connection flags (for preparing relevant statements) std::mutex m_Mutex; diff --git a/src/server/database/Database/MySQLThreading.h b/src/server/database/Database/MySQLThreading.h index 1cfa11d7e5b..b6083500989 100644 --- a/src/server/database/Database/MySQLThreading.h +++ b/src/server/database/Database/MySQLThreading.h @@ -20,7 +20,7 @@ #include "Log.h" -class MySQL +class TC_DATABASE_API MySQL { public: static void Library_Init() diff --git a/src/server/database/Database/PreparedStatement.cpp b/src/server/database/Database/PreparedStatement.cpp index 848a923c75d..119f1d4c93b 100644 --- a/src/server/database/Database/PreparedStatement.cpp +++ b/src/server/database/Database/PreparedStatement.cpp @@ -344,7 +344,7 @@ void MySQLPreparedStatement::setString(const uint8 index, const char* value) CheckValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - size_t len = strlen(value) + 1; + uint32 len = uint32(strlen(value) + 1); param->buffer_type = MYSQL_TYPE_VAR_STRING; delete [] static_cast<char *>(param->buffer); param->buffer = new char[len]; diff --git a/src/server/database/Database/PreparedStatement.h b/src/server/database/Database/PreparedStatement.h index 7d6c98463d0..faaec27014f 100644 --- a/src/server/database/Database/PreparedStatement.h +++ b/src/server/database/Database/PreparedStatement.h @@ -70,7 +70,7 @@ struct PreparedStatementData class MySQLPreparedStatement; //- Upper-level class that is used in code -class PreparedStatement +class TC_DATABASE_API PreparedStatement { friend class PreparedStatementTask; friend class MySQLPreparedStatement; @@ -109,7 +109,7 @@ class PreparedStatement //- Class of which the instances are unique per MySQLConnection //- access to these class objects is only done when a prepared statement task //- is executed. -class MySQLPreparedStatement +class TC_DATABASE_API MySQLPreparedStatement { friend class MySQLConnection; friend class PreparedStatement; @@ -157,7 +157,7 @@ typedef std::future<PreparedQueryResult> PreparedQueryResultFuture; typedef std::promise<PreparedQueryResult> PreparedQueryResultPromise; //- Lower-level class, enqueuable operation -class PreparedStatementTask : public SQLOperation +class TC_DATABASE_API PreparedStatementTask : public SQLOperation { public: PreparedStatementTask(PreparedStatement* stmt, bool async = false); diff --git a/src/common/Threading/Callback.h b/src/server/database/Database/QueryCallback.h index f7eab57ddda..5f6ae74da4f 100644 --- a/src/common/Threading/Callback.h +++ b/src/server/database/Database/QueryCallback.h @@ -15,8 +15,8 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#ifndef _CALLBACK_H -#define _CALLBACK_H +#ifndef _QUERY_CALLBACK_H +#define _QUERY_CALLBACK_H #include <future> #include "QueryResult.h" @@ -206,4 +206,4 @@ class QueryCallback_2 QueryCallback_2& operator=(QueryCallback_2 const& right) = delete; }; -#endif +#endif // _QUERY_CALLBACK_H diff --git a/src/server/database/Database/QueryHolder.h b/src/server/database/Database/QueryHolder.h index 9a5a03fda42..2446a4db2bd 100644 --- a/src/server/database/Database/QueryHolder.h +++ b/src/server/database/Database/QueryHolder.h @@ -20,7 +20,7 @@ #include <future> -class SQLQueryHolder +class TC_DATABASE_API SQLQueryHolder { friend class SQLQueryHolderTask; private: @@ -46,7 +46,7 @@ class SQLQueryHolder typedef std::future<SQLQueryHolder*> QueryResultHolderFuture; typedef std::promise<SQLQueryHolder*> QueryResultHolderPromise; -class SQLQueryHolderTask : public SQLOperation +class TC_DATABASE_API SQLQueryHolderTask : public SQLOperation { private: SQLQueryHolder* m_holder; diff --git a/src/server/database/Database/QueryResult.cpp b/src/server/database/Database/QueryResult.cpp index f02457f67ca..db9e737830c 100644 --- a/src/server/database/Database/QueryResult.cpp +++ b/src/server/database/Database/QueryResult.cpp @@ -76,7 +76,7 @@ m_length(NULL) std::size_t rowSize = 0; for (uint32 i = 0; i < m_fieldCount; ++i) { - size_t size = Field::SizeForType(&field[i]); + uint32 size = Field::SizeForType(&field[i]); rowSize += size; m_rBind[i].buffer_type = field[i].type; diff --git a/src/server/database/Database/QueryResult.h b/src/server/database/Database/QueryResult.h index d4d63b5ec85..3b1691db1a6 100644 --- a/src/server/database/Database/QueryResult.h +++ b/src/server/database/Database/QueryResult.h @@ -27,7 +27,7 @@ #endif #include <mysql.h> -class ResultSet +class TC_DATABASE_API ResultSet { public: ResultSet(MYSQL_RES* result, MYSQL_FIELD* fields, uint64 rowCount, uint32 fieldCount); @@ -60,7 +60,7 @@ class ResultSet typedef std::shared_ptr<ResultSet> QueryResult; -class PreparedResultSet +class TC_DATABASE_API PreparedResultSet { public: PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES* result, uint64 rowCount, uint32 fieldCount); diff --git a/src/server/database/Database/SQLOperation.h b/src/server/database/Database/SQLOperation.h index f0500d1f232..5b3032eab87 100644 --- a/src/server/database/Database/SQLOperation.h +++ b/src/server/database/Database/SQLOperation.h @@ -53,7 +53,7 @@ union SQLResultSetUnion class MySQLConnection; -class SQLOperation +class TC_DATABASE_API SQLOperation { public: SQLOperation(): m_conn(NULL) { } diff --git a/src/server/database/Database/Transaction.h b/src/server/database/Database/Transaction.h index 5780c0363d9..7b5b6addfe4 100644 --- a/src/server/database/Database/Transaction.h +++ b/src/server/database/Database/Transaction.h @@ -25,7 +25,7 @@ class PreparedStatement; /*! Transactions, high level class. */ -class Transaction +class TC_DATABASE_API Transaction { friend class TransactionTask; friend class MySQLConnection; @@ -58,7 +58,7 @@ class Transaction typedef std::shared_ptr<Transaction> SQLTransaction; /*! Low level class*/ -class TransactionTask : public SQLOperation +class TC_DATABASE_API TransactionTask : public SQLOperation { template <class T> friend class DatabaseWorkerPool; friend class DatabaseWorker; diff --git a/src/server/database/Logging/AppenderDB.h b/src/server/database/Logging/AppenderDB.h index a6acc66b48c..225ae969802 100644 --- a/src/server/database/Logging/AppenderDB.h +++ b/src/server/database/Logging/AppenderDB.h @@ -20,7 +20,7 @@ #include "Appender.h" -class AppenderDB: public Appender +class TC_DATABASE_API AppenderDB: public Appender { public: typedef std::integral_constant<AppenderType, APPENDER_DB>::type TypeIndex; diff --git a/src/server/database/Updater/DBUpdater.cpp b/src/server/database/Updater/DBUpdater.cpp index 170954a86f4..8515da9f6f8 100644 --- a/src/server/database/Updater/DBUpdater.cpp +++ b/src/server/database/Updater/DBUpdater.cpp @@ -21,57 +21,41 @@ #include "UpdateFetcher.h" #include "DatabaseLoader.h" #include "Config.h" +#include "BuiltInConfig.h" +#include "StartProcess.h" #include <fstream> #include <iostream> #include <unordered_map> -#include <boost/process.hpp> -#include <boost/iostreams/stream.hpp> -#include <boost/iostreams/copy.hpp> -#include <boost/iostreams/device/file_descriptor.hpp> -#include <boost/system/system_error.hpp> -using namespace boost::process; -using namespace boost::process::initializers; -using namespace boost::iostreams; - -std::string DBUpdaterUtil::GetMySqlCli() +std::string DBUpdaterUtil::GetCorrectedMySQLExecutable() { if (!corrected_path().empty()) return corrected_path(); else - { - std::string const entry = sConfigMgr->GetStringDefault("Updates.MySqlCLIPath", ""); - if (!entry.empty()) - return entry; - else - return GitRevision::GetMySQLExecutable(); - } + return BuiltInConfig::GetMySQLExecutable(); } bool DBUpdaterUtil::CheckExecutable() { - boost::filesystem::path exe(GetMySqlCli()); + boost::filesystem::path exe(GetCorrectedMySQLExecutable()); if (!exists(exe)) { exe.clear(); - try - { - exe = search_path("mysql"); - } - catch (std::runtime_error&) + if (auto path = Trinity::SearchExecutableInPath("mysql")) { - } + exe = std::move(*path); - if (!exe.empty() && exists(exe)) - { - // Correct the path to the cli - corrected_path() = absolute(exe).generic_string(); - return true; + if (!exe.empty() && exists(exe)) + { + // Correct the path to the cli + corrected_path() = absolute(exe).generic_string(); + return true; + } } - TC_LOG_FATAL("sql.updates", "Didn't find executeable mysql binary at \'%s\' or in path, correct the path in the *.conf (\"Updates.MySqlCLIPath\").", + TC_LOG_FATAL("sql.updates", "Didn't find any executable MySQL binary at \'%s\' or in path, correct the path in the *.conf (\"MySQLExecutable\").", absolute(exe).generic_string().c_str()); return false; @@ -85,16 +69,6 @@ std::string& DBUpdaterUtil::corrected_path() return path; } -template<class T> -std::string DBUpdater<T>::GetSourceDirectory() -{ - std::string const entry = sConfigMgr->GetStringDefault("Updates.SourcePath", ""); - if (!entry.empty()) - return entry; - else - return GitRevision::GetSourceDirectory(); -} - // Auth Database template<> std::string DBUpdater<LoginDatabaseConnection>::GetConfigEntry() @@ -111,7 +85,8 @@ std::string DBUpdater<LoginDatabaseConnection>::GetTableName() template<> std::string DBUpdater<LoginDatabaseConnection>::GetBaseFile() { - return DBUpdater<LoginDatabaseConnection>::GetSourceDirectory() + "/sql/base/auth_database.sql"; + return BuiltInConfig::GetSourceDirectory() + + "/sql/base/auth_database.sql"; } template<> @@ -169,7 +144,8 @@ std::string DBUpdater<CharacterDatabaseConnection>::GetTableName() template<> std::string DBUpdater<CharacterDatabaseConnection>::GetBaseFile() { - return DBUpdater<CharacterDatabaseConnection>::GetSourceDirectory() + "/sql/base/characters_database.sql"; + return BuiltInConfig::GetSourceDirectory() + + "/sql/base/characters_database.sql"; } template<> @@ -202,7 +178,7 @@ bool DBUpdater<T>::Create(DatabaseWorkerPool<T>& pool) // Path of temp file static Path const temp("create_table.sql"); - // Create temporary query to use external mysql cli + // Create temporary query to use external MySQL CLi std::ofstream file(temp.generic_string()); if (!file.is_open()) { @@ -221,7 +197,7 @@ bool DBUpdater<T>::Create(DatabaseWorkerPool<T>& pool) } catch (UpdateException&) { - TC_LOG_FATAL("sql.updates", "Failed to create database %s! Has the user `CREATE` priviliges?", pool.GetConnectionInfo()->database.c_str()); + TC_LOG_FATAL("sql.updates", "Failed to create database %s! Does the user (named in *.conf) have `CREATE` privileges on the MySQL server?", pool.GetConnectionInfo()->database.c_str()); boost::filesystem::remove(temp); return false; } @@ -239,7 +215,7 @@ bool DBUpdater<T>::Update(DatabaseWorkerPool<T>& pool) TC_LOG_INFO("sql.updates", "Updating %s database...", DBUpdater<T>::GetTableName().c_str()); - Path const sourceDirectory(GetSourceDirectory()); + Path const sourceDirectory(BuiltInConfig::GetSourceDirectory()); if (!is_directory(sourceDirectory)) { @@ -304,7 +280,7 @@ bool DBUpdater<T>::Populate(DatabaseWorkerPool<T>& pool) { case LOCATION_REPOSITORY: { - TC_LOG_ERROR("sql.updates", ">> Base file \"%s\" is missing, try to clone the source again.", + TC_LOG_ERROR("sql.updates", ">> Base file \"%s\" is missing. Try fixing it by cloning the source again.", base.generic_string().c_str()); break; @@ -312,7 +288,7 @@ bool DBUpdater<T>::Populate(DatabaseWorkerPool<T>& pool) case LOCATION_DOWNLOAD: { TC_LOG_ERROR("sql.updates", ">> File \"%s\" is missing, download it from \"https://github.com/TrinityCore/TrinityCore/releases\"" \ - " and place it in your server directory.", base.filename().generic_string().c_str()); + " uncompress it and place the file TDB_full_world_(a_variable_name).sql in your worldserver directory.", base.filename().generic_string().c_str()); break; } } @@ -379,7 +355,7 @@ void DBUpdater<T>::ApplyFile(DatabaseWorkerPool<T>& pool, std::string const& hos if (!std::isdigit(port_or_socket[0])) { - // We can't check here if host == "." because is named localhost if socket option is enabled + // We can't check if host == "." here, because it is named localhost if socket option is enabled args.push_back("-P0"); args.push_back("--protocol=SOCKET"); args.push_back("-S" + port_or_socket); @@ -400,55 +376,23 @@ void DBUpdater<T>::ApplyFile(DatabaseWorkerPool<T>& pool, std::string const& hos if (!database.empty()) args.push_back(database); - // ToDo: use the existing query in memory as virtual file if possible - file_descriptor_source source(path); - - uint32 ret; - try - { - boost::process::pipe outPipe = create_pipe(); - boost::process::pipe errPipe = create_pipe(); - - child c = execute(run_exe( - boost::filesystem::absolute(DBUpdaterUtil::GetMySqlCli()).generic_string()), - set_args(args), bind_stdin(source), throw_on_error(), - bind_stdout(file_descriptor_sink(outPipe.sink, close_handle)), - bind_stderr(file_descriptor_sink(errPipe.sink, close_handle))); - - file_descriptor_source mysqlOutfd(outPipe.source, close_handle); - file_descriptor_source mysqlErrfd(errPipe.source, close_handle); - - stream<file_descriptor_source> mysqlOutStream(mysqlOutfd); - stream<file_descriptor_source> mysqlErrStream(mysqlErrfd); - - std::stringstream out; - std::stringstream err; - - copy(mysqlOutStream, out); - copy(mysqlErrStream, err); - - TC_LOG_INFO("sql.updates", "%s", out.str().c_str()); - TC_LOG_ERROR("sql.updates", "%s", err.str().c_str()); - - ret = wait_for_exit(c); - } - catch (boost::system::system_error&) - { - ret = EXIT_FAILURE; - } - - source.close(); + // Invokes a mysql process which doesn't leak credentials to logs + int const ret = Trinity::StartProcess(DBUpdaterUtil::GetCorrectedMySQLExecutable(), args, + "sql.updates", path.generic_string(), true); if (ret != EXIT_SUCCESS) { TC_LOG_FATAL("sql.updates", "Applying of file \'%s\' to database \'%s\' failed!" \ - " If you are an user pull the latest revision from the repository. If you are a developer fix your sql query.", + " If you are a user, please pull the latest revision from the repository. " + "Also make sure you have not applied any of the databases with your sql client. " + "You cannot use auto-update system and import sql files from TrinityCore repository with your sql client. " + "If you are a developer, please fix your sql query.", path.generic_string().c_str(), pool.GetConnectionInfo()->database.c_str()); throw UpdateException("update failed"); } } -template class DBUpdater<LoginDatabaseConnection>; -template class DBUpdater<WorldDatabaseConnection>; -template class DBUpdater<CharacterDatabaseConnection>; +template class TC_DATABASE_API DBUpdater<LoginDatabaseConnection>; +template class TC_DATABASE_API DBUpdater<WorldDatabaseConnection>; +template class TC_DATABASE_API DBUpdater<CharacterDatabaseConnection>; diff --git a/src/server/database/Updater/DBUpdater.h b/src/server/database/Updater/DBUpdater.h index c9792ffe060..cc5d3aad68b 100644 --- a/src/server/database/Updater/DBUpdater.h +++ b/src/server/database/Updater/DBUpdater.h @@ -23,7 +23,7 @@ #include <string> #include <boost/filesystem.hpp> -class UpdateException : public std::exception +class TC_DATABASE_API UpdateException : public std::exception { public: UpdateException(std::string const& msg) : _msg(msg) { } @@ -41,7 +41,7 @@ enum BaseLocation LOCATION_DOWNLOAD }; -struct UpdateResult +struct TC_DATABASE_API UpdateResult { UpdateResult() : updated(0), recent(0), archived(0) { } @@ -57,7 +57,7 @@ struct UpdateResult class DBUpdaterUtil { public: - static std::string GetMySqlCli(); + static std::string GetCorrectedMySQLExecutable(); static bool CheckExecutable(); @@ -66,13 +66,11 @@ private: }; template <class T> -class DBUpdater +class TC_DATABASE_API DBUpdater { public: using Path = boost::filesystem::path; - static std::string GetSourceDirectory(); - static inline std::string GetConfigEntry(); static inline std::string GetTableName(); diff --git a/src/server/database/Updater/UpdateFetcher.cpp b/src/server/database/Updater/UpdateFetcher.cpp index fd0dbdd4b5a..7dc0a307ca2 100644 --- a/src/server/database/Updater/UpdateFetcher.cpp +++ b/src/server/database/Updater/UpdateFetcher.cpp @@ -18,6 +18,7 @@ #include "UpdateFetcher.h" #include "Log.h" #include "Util.h" +#include "SHA1.h" #include <fstream> #include <chrono> @@ -25,7 +26,6 @@ #include <sstream> #include <exception> #include <unordered_map> -#include <openssl/sha.h> using namespace boost::filesystem; @@ -137,24 +137,33 @@ UpdateFetcher::AppliedFileStorage UpdateFetcher::ReceiveAppliedFiles() const return map; } -UpdateFetcher::SQLUpdate UpdateFetcher::ReadSQLUpdate(boost::filesystem::path const& file) const +std::string UpdateFetcher::ReadSQLUpdate(boost::filesystem::path const& file) const { std::ifstream in(file.c_str()); - WPFatal(in.is_open(), "Could not read an update file."); + if (!in.is_open()) + { + TC_LOG_FATAL("sql.updates", "Failed to open the sql update \"%s\" for reading! " + "Stopping the server to keep the database integrity, " + "try to identify and solve the issue or disabled the database updater.", + file.generic_string().c_str()); - auto const start_pos = in.tellg(); - in.ignore(std::numeric_limits<std::streamsize>::max()); - auto const char_count = in.gcount(); - in.seekg(start_pos); + throw UpdateException("Opening the sql update failed!"); + } - SQLUpdate const update(new std::string(char_count, char{})); + auto update = [&in] { + std::ostringstream ss; + ss << in.rdbuf(); + return ss.str(); + }(); - in.read(&(*update)[0], update->size()); in.close(); return update; } -UpdateResult UpdateFetcher::Update(bool const redundancyChecks, bool const allowRehash, bool const archivedRedundancy, int32 const cleanDeadReferencesMaxCount) const +UpdateResult UpdateFetcher::Update(bool const redundancyChecks, + bool const allowRehash, + bool const archivedRedundancy, + int32 const cleanDeadReferencesMaxCount) const { LocaleFileStorage const available = GetFileList(); AppliedFileStorage applied = ReceiveAppliedFiles(); @@ -200,11 +209,8 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, bool const allow } } - // Read update from file - SQLUpdate const update = ReadSQLUpdate(availableQuery.first); - - // Calculate hash - std::string const hash = CalculateHash(update); + // Calculate a Sha1 hash based on query content. + std::string const hash = CalculateSHA1Hash(ReadSQLUpdate(availableQuery.first)); UpdateMode mode = MODE_APPLY; @@ -327,15 +333,6 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, bool const allow return UpdateResult(importedUpdates, countRecentUpdates, countArchivedUpdates); } -std::string UpdateFetcher::CalculateHash(SQLUpdate const& query) const -{ - // Calculate a Sha1 hash based on query content. - unsigned char digest[SHA_DIGEST_LENGTH]; - SHA1((unsigned char*)query->c_str(), query->length(), (unsigned char*)&digest); - - return ByteArrayToHexStr(digest, SHA_DIGEST_LENGTH); -} - uint32 UpdateFetcher::Apply(Path const& path) const { using Time = std::chrono::high_resolution_clock; @@ -347,7 +344,7 @@ uint32 UpdateFetcher::Apply(Path const& path) const _applyFile(path); // Return time the query took to apply - return std::chrono::duration_cast<std::chrono::milliseconds>(Time::now() - begin).count(); + return uint32(std::chrono::duration_cast<std::chrono::milliseconds>(Time::now() - begin).count()); } void UpdateFetcher::UpdateEntry(AppliedFileEntry const& entry, uint32 const speed) const diff --git a/src/server/database/Updater/UpdateFetcher.h b/src/server/database/Updater/UpdateFetcher.h index 22a0d08c7f8..cabc3c2fce3 100644 --- a/src/server/database/Updater/UpdateFetcher.h +++ b/src/server/database/Updater/UpdateFetcher.h @@ -25,7 +25,7 @@ #include <memory> #include <vector> -class UpdateFetcher +class TC_DATABASE_API UpdateFetcher { typedef boost::filesystem::path Path; @@ -103,16 +103,15 @@ private: typedef std::unordered_map<std::string, std::string> HashToFileNameStorage; typedef std::unordered_map<std::string, AppliedFileEntry> AppliedFileStorage; typedef std::vector<UpdateFetcher::DirectoryEntry> DirectoryStorage; - typedef std::shared_ptr<std::string> SQLUpdate; LocaleFileStorage GetFileList() const; - void FillFileListRecursively(Path const& path, LocaleFileStorage& storage, State const state, uint32 const depth) const; + void FillFileListRecursively(Path const& path, LocaleFileStorage& storage, + State const state, uint32 const depth) const; DirectoryStorage ReceiveIncludedDirectories() const; AppliedFileStorage ReceiveAppliedFiles() const; - SQLUpdate ReadSQLUpdate(Path const& file) const; - std::string CalculateHash(SQLUpdate const& query) const; + std::string ReadSQLUpdate(Path const& file) const; uint32 Apply(Path const& path) const; diff --git a/src/server/game/AI/CoreAI/CombatAI.cpp b/src/server/game/AI/CoreAI/CombatAI.cpp index 716ac13c666..4d0247d9fb5 100644 --- a/src/server/game/AI/CoreAI/CombatAI.cpp +++ b/src/server/game/AI/CoreAI/CombatAI.cpp @@ -50,7 +50,7 @@ void AggressorAI::UpdateAI(uint32 /*diff*/) void CombatAI::InitializeAI() { - for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i = 0; i < MAX_CREATURE_SPELLS; ++i) if (me->m_spells[i] && sSpellMgr->GetSpellInfo(me->m_spells[i])) spells.push_back(me->m_spells[i]); diff --git a/src/server/game/AI/CoreAI/CombatAI.h b/src/server/game/AI/CoreAI/CombatAI.h index 55b91b6969e..f1718fbdb6a 100644 --- a/src/server/game/AI/CoreAI/CombatAI.h +++ b/src/server/game/AI/CoreAI/CombatAI.h @@ -25,7 +25,7 @@ class Creature; -class AggressorAI : public CreatureAI +class TC_GAME_API AggressorAI : public CreatureAI { public: explicit AggressorAI(Creature* c) : CreatureAI(c) { } @@ -36,7 +36,7 @@ class AggressorAI : public CreatureAI typedef std::vector<uint32> SpellVct; -class CombatAI : public CreatureAI +class TC_GAME_API CombatAI : public CreatureAI { public: explicit CombatAI(Creature* c) : CreatureAI(c) { } @@ -55,7 +55,7 @@ class CombatAI : public CreatureAI SpellVct spells; }; -class CasterAI : public CombatAI +class TC_GAME_API CasterAI : public CombatAI { public: explicit CasterAI(Creature* c) : CombatAI(c) { m_attackDist = MELEE_RANGE; } @@ -67,7 +67,7 @@ class CasterAI : public CombatAI float m_attackDist; }; -struct ArcherAI : public CreatureAI +struct TC_GAME_API ArcherAI : public CreatureAI { public: explicit ArcherAI(Creature* c); @@ -80,7 +80,7 @@ struct ArcherAI : public CreatureAI float m_minRange; }; -struct TurretAI : public CreatureAI +struct TC_GAME_API TurretAI : public CreatureAI { public: explicit TurretAI(Creature* c); @@ -97,7 +97,7 @@ struct TurretAI : public CreatureAI #define VEHICLE_CONDITION_CHECK_TIME 1000 #define VEHICLE_DISMISS_TIME 5000 -struct VehicleAI : public CreatureAI +struct TC_GAME_API VehicleAI : public CreatureAI { public: explicit VehicleAI(Creature* creature); diff --git a/src/server/game/AI/CoreAI/GameObjectAI.h b/src/server/game/AI/CoreAI/GameObjectAI.h index 4f256a5de31..7a2f23ac804 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.h +++ b/src/server/game/AI/CoreAI/GameObjectAI.h @@ -26,7 +26,7 @@ #include "GameObject.h" #include "CreatureAI.h" -class GameObjectAI +class TC_GAME_API GameObjectAI { protected: GameObject* const go; @@ -63,7 +63,7 @@ class GameObjectAI virtual void EventInform(uint32 /*eventId*/) { } }; -class NullGameObjectAI : public GameObjectAI +class TC_GAME_API NullGameObjectAI : public GameObjectAI { public: explicit NullGameObjectAI(GameObject* g); diff --git a/src/server/game/AI/CoreAI/GuardAI.h b/src/server/game/AI/CoreAI/GuardAI.h index 63f2750a5d4..a6aa4b6624a 100644 --- a/src/server/game/AI/CoreAI/GuardAI.h +++ b/src/server/game/AI/CoreAI/GuardAI.h @@ -23,7 +23,7 @@ class Creature; -class GuardAI : public ScriptedAI +class TC_GAME_API GuardAI : public ScriptedAI { public: explicit GuardAI(Creature* creature); diff --git a/src/server/game/AI/CoreAI/PassiveAI.cpp b/src/server/game/AI/CoreAI/PassiveAI.cpp index aafde3c1d9a..3ed2f927645 100644 --- a/src/server/game/AI/CoreAI/PassiveAI.cpp +++ b/src/server/game/AI/CoreAI/PassiveAI.cpp @@ -58,6 +58,12 @@ void PossessedAI::KilledUnit(Unit* victim) victim->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } +void PossessedAI::OnCharmed(bool /*apply*/) +{ + me->NeedChangeAI = true; + me->IsAIEnabled = false; +} + void CritterAI::DamageTaken(Unit* /*done_by*/, uint32&) { if (!me->HasUnitState(UNIT_STATE_FLEEING)) diff --git a/src/server/game/AI/CoreAI/PassiveAI.h b/src/server/game/AI/CoreAI/PassiveAI.h index bd72cd7fbe7..9ca9e75bd9f 100644 --- a/src/server/game/AI/CoreAI/PassiveAI.h +++ b/src/server/game/AI/CoreAI/PassiveAI.h @@ -21,7 +21,7 @@ #include "CreatureAI.h" -class PassiveAI : public CreatureAI +class TC_GAME_API PassiveAI : public CreatureAI { public: explicit PassiveAI(Creature* c); @@ -33,7 +33,7 @@ class PassiveAI : public CreatureAI static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; -class PossessedAI : public CreatureAI +class TC_GAME_API PossessedAI : public CreatureAI { public: explicit PossessedAI(Creature* c); @@ -46,10 +46,12 @@ class PossessedAI : public CreatureAI void JustDied(Unit*) override; void KilledUnit(Unit* victim) override; + void OnCharmed(bool /*apply*/) override; + static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; -class NullCreatureAI : public CreatureAI +class TC_GAME_API NullCreatureAI : public CreatureAI { public: explicit NullCreatureAI(Creature* c); @@ -63,7 +65,7 @@ class NullCreatureAI : public CreatureAI static int Permissible(const Creature*) { return PERMIT_BASE_IDLE; } }; -class CritterAI : public PassiveAI +class TC_GAME_API CritterAI : public PassiveAI { public: explicit CritterAI(Creature* c) : PassiveAI(c) { } @@ -72,7 +74,7 @@ class CritterAI : public PassiveAI void EnterEvadeMode(EvadeReason why) override; }; -class TriggerAI : public NullCreatureAI +class TC_GAME_API TriggerAI : public NullCreatureAI { public: explicit TriggerAI(Creature* c) : NullCreatureAI(c) { } diff --git a/src/server/game/AI/CoreAI/PetAI.cpp b/src/server/game/AI/CoreAI/PetAI.cpp index 8acf6b9c9dc..2abe20f0ae6 100644 --- a/src/server/game/AI/CoreAI/PetAI.cpp +++ b/src/server/game/AI/CoreAI/PetAI.cpp @@ -150,14 +150,14 @@ void PetAI::UpdateAI(uint32 diff) if (me->GetCharmInfo() && me->GetSpellHistory()->HasGlobalCooldown(spellInfo)) continue; + // check spell cooldown + if (!me->GetSpellHistory()->IsReady(spellInfo)) + continue; + if (spellInfo->IsPositive()) { if (spellInfo->CanBeUsedInCombat()) { - // check spell cooldown & school lock - if (!me->GetSpellHistory()->IsReady(spellInfo)) - continue; - // Check if we're in combat or commanded to attack if (!me->IsInCombat() && !me->GetCharmInfo()->IsCommandAttack()) continue; @@ -225,26 +225,17 @@ void PetAI::UpdateAI(uint32 diff) //found units to cast on to if (!targetSpellStore.empty()) { - uint32 index = urand(0, targetSpellStore.size() - 1); + TargetSpellList::iterator it = targetSpellStore.begin(); + std::advance(it, urand(0, targetSpellStore.size() - 1)); - Spell* spell = targetSpellStore[index].second; - Unit* target = targetSpellStore[index].first; + Spell* spell = (*it).second; + Unit* target = (*it).first; - targetSpellStore.erase(targetSpellStore.begin() + index); + targetSpellStore.erase(it); SpellCastTargets targets; targets.SetUnitTarget(target); - if (!me->HasInArc(float(M_PI), target)) - { - me->SetInFront(target); - if (target && target->GetTypeId() == TYPEID_PLAYER) - me->SendUpdateToPlayer(target->ToPlayer()); - - if (owner && owner->GetTypeId() == TYPEID_PLAYER) - me->SendUpdateToPlayer(owner->ToPlayer()); - } - spell->prepare(&targets); } @@ -254,9 +245,9 @@ void PetAI::UpdateAI(uint32 diff) } // Update speed as needed to prevent dropping too far behind and despawning - me->UpdateSpeed(MOVE_RUN, true); - me->UpdateSpeed(MOVE_WALK, true); - me->UpdateSpeed(MOVE_FLIGHT, true); + me->UpdateSpeed(MOVE_RUN); + me->UpdateSpeed(MOVE_WALK); + me->UpdateSpeed(MOVE_FLIGHT); } @@ -597,6 +588,12 @@ void PetAI::ReceiveEmote(Player* player, uint32 emote) } } +void PetAI::OnCharmed(bool /*apply*/) +{ + me->NeedChangeAI = true; + me->IsAIEnabled = false; +} + void PetAI::ClearCharmInfoFlags() { // Quick access to set all flags to FALSE diff --git a/src/server/game/AI/CoreAI/PetAI.h b/src/server/game/AI/CoreAI/PetAI.h index 9c33baa9a9f..93ee6c41ece 100644 --- a/src/server/game/AI/CoreAI/PetAI.h +++ b/src/server/game/AI/CoreAI/PetAI.h @@ -25,7 +25,7 @@ class Creature; class Spell; -class PetAI : public CreatureAI +class TC_GAME_API PetAI : public CreatureAI { public: @@ -49,6 +49,8 @@ class PetAI : public CreatureAI void MoveInLineOfSight_Safe(Unit* /*who*/) { } // CreatureAI interferes with returning pets void EnterEvadeMode(EvadeReason /*why*/) override { } // For fleeing, pets don't use this type of Evade mechanic + void OnCharmed(bool /*apply*/) override; + private: bool _isVisible(Unit*) const; bool _needToStop(void); diff --git a/src/server/game/AI/CoreAI/ReactorAI.h b/src/server/game/AI/CoreAI/ReactorAI.h index e5abaac2f00..d281ca11fdf 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.h +++ b/src/server/game/AI/CoreAI/ReactorAI.h @@ -23,7 +23,7 @@ class Unit; -class ReactorAI : public CreatureAI +class TC_GAME_API ReactorAI : public CreatureAI { public: diff --git a/src/server/game/AI/CoreAI/TotemAI.h b/src/server/game/AI/CoreAI/TotemAI.h index e1d1618037f..a0e796ed7e0 100644 --- a/src/server/game/AI/CoreAI/TotemAI.h +++ b/src/server/game/AI/CoreAI/TotemAI.h @@ -25,7 +25,7 @@ class Creature; class Totem; -class TotemAI : public CreatureAI +class TC_GAME_API TotemAI : public CreatureAI { public: diff --git a/src/server/game/AI/CoreAI/UnitAI.cpp b/src/server/game/AI/CoreAI/UnitAI.cpp index a3a5e7f7663..037d9e59cf2 100644 --- a/src/server/game/AI/CoreAI/UnitAI.cpp +++ b/src/server/game/AI/CoreAI/UnitAI.cpp @@ -259,73 +259,67 @@ void UnitAI::FillAISpellInfo() } } -//Enable PlayerAI when charmed -void PlayerAI::OnCharmed(bool apply) +SpellTargetSelector::SpellTargetSelector(Unit* caster, uint32 spellId) : + _caster(caster), _spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(spellId), caster)) { - me->IsAIEnabled = apply; + ASSERT(_spellInfo); } -void SimpleCharmedAI::UpdateAI(const uint32 /*diff*/) +bool SpellTargetSelector::operator()(Unit const* target) const { - Creature* charmer = me->GetCharmer()->ToCreature(); + if (!target || _spellInfo->CheckTarget(_caster, target) != SPELL_CAST_OK) + return false; - //kill self if charm aura has infinite duration - if (charmer->IsInEvadeMode()) + // copypasta from Spell::CheckRange + float minRange = 0.0f; + float maxRange = 0.0f; + float rangeMod = 0.0f; + if (_spellInfo->RangeEntry) { - Unit::AuraEffectList const& auras = me->GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); - for (Unit::AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) - if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) + if (_spellInfo->RangeEntry->type & SPELL_RANGE_MELEE) + { + rangeMod = _caster->GetCombatReach() + 4.0f / 3.0f; + rangeMod += target->GetCombatReach(); + + rangeMod = std::max(rangeMod, NOMINAL_MELEE_RANGE); + } + else + { + float meleeRange = 0.0f; + if (_spellInfo->RangeEntry->type & SPELL_RANGE_RANGED) { - charmer->Kill(me); - return; + meleeRange = _caster->GetCombatReach() + 4.0f / 3.0f; + meleeRange += target->GetCombatReach(); + + meleeRange = std::max(meleeRange, NOMINAL_MELEE_RANGE); } - } - if (!charmer->IsInCombat()) - me->GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, me->GetFollowAngle()); + minRange = _caster->GetSpellMinRangeForTarget(target, _spellInfo) + meleeRange; + maxRange = _caster->GetSpellMaxRangeForTarget(target, _spellInfo); - Unit* target = me->GetVictim(); - if (!target || !charmer->IsValidAttackTarget(target)) - AttackStart(charmer->SelectNearestTargetInAttackDistance()); -} + rangeMod = _caster->GetCombatReach(); + rangeMod += target->GetCombatReach(); -SpellTargetSelector::SpellTargetSelector(Unit* caster, uint32 spellId) : - _caster(caster), _spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(spellId), caster)) -{ - ASSERT(_spellInfo); -} - -bool SpellTargetSelector::operator()(Unit const* target) const -{ - if (!target) - return false; + if (minRange > 0.0f && !(_spellInfo->RangeEntry->type & SPELL_RANGE_RANGED)) + minRange += rangeMod; + } - if (_spellInfo->CheckTarget(_caster, target) != SPELL_CAST_OK) - return false; + if (_caster->isMoving() && target->isMoving() && !_caster->IsWalking() && !target->IsWalking() && + (_spellInfo->RangeEntry->type & SPELL_RANGE_MELEE || target->GetTypeId() == TYPEID_PLAYER)) + rangeMod += 5.0f / 3.0f; + } - // copypasta from Spell::CheckRange - uint32 range_type = _spellInfo->RangeEntry ? _spellInfo->RangeEntry->type : 0; - float max_range = _caster->GetSpellMaxRangeForTarget(target, _spellInfo); - float min_range = _caster->GetSpellMinRangeForTarget(target, _spellInfo); + maxRange += rangeMod; + minRange *= minRange; + maxRange *= maxRange; - if (target && target != _caster) + if (target != _caster) { - if (range_type == SPELL_RANGE_MELEE) - { - // Because of lag, we can not check too strictly here. - if (!_caster->IsWithinMeleeRange(target, max_range)) - return false; - } - else if (!_caster->IsWithinCombatRange(target, max_range)) + if (_caster->GetExactDistSq(target) > maxRange) return false; - if (range_type == SPELL_RANGE_RANGED) - { - if (_caster->IsWithinMeleeRange(target)) - return false; - } - else if (min_range && _caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0 + if (minRange > 0.0f && _caster->GetExactDistSq(target) < minRange) return false; } @@ -340,5 +334,8 @@ bool NonTankTargetSelector::operator()(Unit const* target) const if (_playerOnly && target->GetTypeId() != TYPEID_PLAYER) return false; + if (HostileReference* currentVictim = _source->getThreatManager().getCurrentVictim()) + return target->GetGUID() != currentVictim->getUnitGuid(); + return target != _source->GetVictim(); } diff --git a/src/server/game/AI/CoreAI/UnitAI.h b/src/server/game/AI/CoreAI/UnitAI.h index 5dc5946b226..0dd09bc8051 100644 --- a/src/server/game/AI/CoreAI/UnitAI.h +++ b/src/server/game/AI/CoreAI/UnitAI.h @@ -40,7 +40,7 @@ enum SelectAggroTarget }; // default predicate function to select target based on distance, player and/or aura criteria -struct DefaultTargetSelector : public std::unary_function<Unit*, bool> +struct TC_GAME_API DefaultTargetSelector : public std::unary_function<Unit*, bool> { const Unit* me; float m_dist; @@ -90,7 +90,7 @@ struct DefaultTargetSelector : public std::unary_function<Unit*, bool> // Target selector for spell casts checking range, auras and attributes /// @todo Add more checks from Spell::CheckCast -struct SpellTargetSelector : public std::unary_function<Unit*, bool> +struct TC_GAME_API SpellTargetSelector : public std::unary_function<Unit*, bool> { public: SpellTargetSelector(Unit* caster, uint32 spellId); @@ -104,18 +104,18 @@ struct SpellTargetSelector : public std::unary_function<Unit*, bool> // Very simple target selector, will just skip main target // NOTE: When passing to UnitAI::SelectTarget remember to use 0 as position for random selection // because tank will not be in the temporary list -struct NonTankTargetSelector : public std::unary_function<Unit*, bool> +struct TC_GAME_API NonTankTargetSelector : public std::unary_function<Unit*, bool> { public: - NonTankTargetSelector(Creature* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } + NonTankTargetSelector(Unit* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } bool operator()(Unit const* target) const; private: - Creature const* _source; + Unit* _source; bool _playerOnly; }; -class UnitAI +class TC_GAME_API UnitAI { protected: Unit* const me; @@ -148,15 +148,29 @@ class UnitAI { ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); if (position >= threatlist.size()) - return NULL; + return nullptr; std::list<Unit*> targetList; + Unit* currentVictim = nullptr; + if (auto currentVictimReference = me->getThreatManager().getCurrentVictim()) + { + currentVictim = currentVictimReference->getTarget(); + + // Current victim always goes first + if (currentVictim && predicate(currentVictim)) + targetList.push_back(currentVictim); + } + for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - if (predicate((*itr)->getTarget())) + { + if (currentVictim != nullptr && (*itr)->getTarget() != currentVictim && predicate((*itr)->getTarget())) + targetList.push_back((*itr)->getTarget()); + else if (currentVictim == nullptr && predicate((*itr)->getTarget())) targetList.push_back((*itr)->getTarget()); + } if (position >= targetList.size()) - return NULL; + return nullptr; if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) targetList.sort(Trinity::ObjectDistanceOrderPred(me)); @@ -187,7 +201,7 @@ class UnitAI break; } - return NULL; + return nullptr; } void SelectTargetList(std::list<Unit*>& targetList, uint32 num, SelectAggroTarget targetType, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); @@ -242,6 +256,7 @@ class UnitAI void DoAddAuraToAllHostilePlayers(uint32 spellid); void DoCast(uint32 spellId); void DoCast(Unit* victim, uint32 spellId, bool triggered = false); + void DoCastSelf(uint32 spellId, bool triggered = false) { DoCast(me, spellId, triggered); } void DoCastToAllHostilePlayers(uint32 spellid, bool triggered = false); void DoCastVictim(uint32 spellId, bool triggered = false); void DoCastAOE(uint32 spellId, bool triggered = false); @@ -268,21 +283,4 @@ class UnitAI UnitAI& operator=(UnitAI const& right) = delete; }; -class PlayerAI : public UnitAI -{ - protected: - Player* const me; - public: - explicit PlayerAI(Player* player) : UnitAI((Unit*)player), me(player) { } - - void OnCharmed(bool apply) override; -}; - -class SimpleCharmedAI : public PlayerAI -{ - public: - void UpdateAI(uint32 diff) override; - SimpleCharmedAI(Player* player): PlayerAI(player) { } -}; - #endif diff --git a/src/server/game/AI/CreatureAI.cpp b/src/server/game/AI/CreatureAI.cpp index 44098586e5f..15bbff2793f 100644 --- a/src/server/game/AI/CreatureAI.cpp +++ b/src/server/game/AI/CreatureAI.cpp @@ -29,11 +29,13 @@ #include "Language.h" //Disable CreatureAI when charmed -void CreatureAI::OnCharmed(bool /*apply*/) +void CreatureAI::OnCharmed(bool apply) { - //me->IsAIEnabled = !apply;*/ - me->NeedChangeAI = true; - me->IsAIEnabled = false; + if (apply) + { + me->NeedChangeAI = true; + me->IsAIEnabled = false; + } } AISpellInfoType* UnitAI::AISpellInfo; @@ -44,7 +46,7 @@ void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= nullptr*/) sCreatureTextMgr->SendChat(me, id, whisperTarget); } -void CreatureAI::DoZoneInCombat(Creature* creature /*= NULL*/, float maxRangeToNearestTarget /* = 50.0f*/) +void CreatureAI::DoZoneInCombat(Creature* creature /*= nullptr*/, float maxRangeToNearestTarget /* = 250.0f*/) { if (!creature) creature = me; @@ -133,7 +135,7 @@ void CreatureAI::MoveInLineOfSight(Unit* who) if (me->GetCreatureType() == CREATURE_TYPE_NON_COMBAT_PET) // non-combat pets should just stand there and look good;) return; - if (me->CanStartAttack(who, false)) + if (me->HasReactState(REACT_AGGRESSIVE) && me->CanStartAttack(who, false)) AttackStart(who); //else if (who->GetVictim() && me->IsFriendlyTo(who) // && me->IsWithinDistInMap(who, sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS)) @@ -257,17 +259,16 @@ bool CreatureAI::_EnterEvadeMode(EvadeReason /*why*/) if (!me->IsAlive()) return false; - // don't remove vehicle auras, passengers aren't supposed to drop off the vehicle - // don't remove clone caster on evade (to be verified) - me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE, SPELL_AURA_CLONE_CASTER); + me->RemoveAurasOnEvade(); // sometimes bosses stuck in combat? me->DeleteThreatList(); me->CombatStop(true); me->LoadCreaturesAddon(); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); me->ResetPlayerDamageReq(); me->SetLastDamagedTime(0); + me->SetCannotReachTarget(false); if (me->IsInEvadeMode()) return false; @@ -275,15 +276,15 @@ bool CreatureAI::_EnterEvadeMode(EvadeReason /*why*/) return true; } -#define BOUNDARY_VISUALIZE_CREATURE 15425 -#define BOUNDARY_VISUALIZE_CREATURE_SCALE 0.25f -#define BOUNDARY_VISUALIZE_STEP_SIZE 1 -#define BOUNDARY_VISUALIZE_FAILSAFE_LIMIT 750 -#define BOUNDARY_VISUALIZE_SPAWN_HEIGHT 5 +static const uint32 BOUNDARY_VISUALIZE_CREATURE = 15425; +static const float BOUNDARY_VISUALIZE_CREATURE_SCALE = 0.25f; +static const int8 BOUNDARY_VISUALIZE_STEP_SIZE = 1; +static const int32 BOUNDARY_VISUALIZE_FAILSAFE_LIMIT = 750; +static const float BOUNDARY_VISUALIZE_SPAWN_HEIGHT = 5.0f; int32 CreatureAI::VisualizeBoundary(uint32 duration, Unit* owner, bool fill) const { typedef std::pair<int32, int32> coordinate; - + if (!owner) return -1; @@ -293,15 +294,15 @@ int32 CreatureAI::VisualizeBoundary(uint32 duration, Unit* owner, bool fill) con std::queue<coordinate> Q; std::unordered_set<coordinate> alreadyChecked; std::unordered_set<coordinate> outOfBounds; - + Position startPosition = owner->GetPosition(); - if (!CheckBoundary(&startPosition)) // fall back to creature position - { + if (!CheckBoundary(&startPosition)) + { // fall back to creature position startPosition = me->GetPosition(); if (!CheckBoundary(&startPosition)) - { + { // fall back to creature home position startPosition = me->GetHomePosition(); - if (!CheckBoundary(&startPosition)) // fall back to creature home position + if (!CheckBoundary(&startPosition)) return LANG_CREATURE_NO_INTERIOR_POINT_FOUND; } } diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index 239fda577a7..f8fa6ba532b 100644 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -28,6 +28,7 @@ class WorldObject; class Unit; class Creature; class Player; +class PlayerAI; class SpellInfo; #define TIME_INTERVAL_LOOK 5000 @@ -65,7 +66,7 @@ enum SCEquip }; typedef std::set<AreaBoundary const*> CreatureBoundary; -class CreatureAI : public UnitAI +class TC_GAME_API CreatureAI : public UnitAI { protected: Creature* const me; @@ -86,6 +87,7 @@ class CreatureAI : public UnitAI { EVADE_REASON_NO_HOSTILES, // the creature's threat list is empty EVADE_REASON_BOUNDARY, // the creature has moved outside its evade boundary + EVADE_REASON_NO_PATH, // the creature was unable to reach its target for over 5 seconds EVADE_REASON_SEQUENCE_BREAK, // this is a boss and the pre-requisite encounters for engaging it are not defeated yet EVADE_REASON_OTHER }; @@ -110,7 +112,7 @@ class CreatureAI : public UnitAI // Called for reaction at stopping attack at no attackers or targets virtual void EnterEvadeMode(EvadeReason why = EVADE_REASON_OTHER); - // Called for reaction at enter to combat if not in combat yet (enemy can be NULL) + // Called for reaction at enter to combat if not in combat yet (enemy can be nullptr) virtual void EnterCombat(Unit* /*victim*/) { } // Called when the creature is killed @@ -136,8 +138,8 @@ class CreatureAI : public UnitAI virtual void AttackedBy(Unit* /*attacker*/) { } virtual bool IsEscorted() const { return false; } - // Called when creature is spawned or respawned (for reseting variables) - virtual void JustRespawned() { Reset(); } + // Called when creature is spawned or respawned + virtual void JustRespawned() { } // Called at waypoint reached or point movement finished virtual void MovementInform(uint32 /*type*/, uint32 /*id*/) { } @@ -147,7 +149,7 @@ class CreatureAI : public UnitAI // Called at reaching home after evade virtual void JustReachedHome() { } - void DoZoneInCombat(Creature* creature = NULL, float maxRangeToNearestTarget = 50.0f); + void DoZoneInCombat(Creature* creature = nullptr, float maxRangeToNearestTarget = 250.0f); // Called at text emote receive from player virtual void ReceiveEmote(Player* /*player*/, uint32 /*emoteId*/) { } @@ -186,6 +188,11 @@ class CreatureAI : public UnitAI virtual bool CanSeeAlways(WorldObject const* /*obj*/) { return false; } + // Called when a player is charmed by the creature + // If a PlayerAI* is returned, that AI is placed on the player instead of the default charm AI + // Object destruction is handled by Unit::RemoveCharmedBy + virtual PlayerAI* GetAIForCharmedPlayer(Player* /*who*/) { return nullptr; } + // intended for encounter design/debugging. do not use for other purposes. expensive. int32 VisualizeBoundary(uint32 duration, Unit* owner=nullptr, bool fill=false) const; virtual bool CheckInRoom(); diff --git a/src/server/game/AI/CreatureAISelector.h b/src/server/game/AI/CreatureAISelector.h index 7c7bc705ade..0e3be1a8604 100644 --- a/src/server/game/AI/CreatureAISelector.h +++ b/src/server/game/AI/CreatureAISelector.h @@ -27,9 +27,9 @@ class GameObject; namespace FactorySelector { - CreatureAI* selectAI(Creature*); - MovementGenerator* selectMovementGenerator(Creature*); - GameObjectAI* SelectGameObjectAI(GameObject*); + TC_GAME_API CreatureAI* selectAI(Creature*); + TC_GAME_API MovementGenerator* selectMovementGenerator(Creature*); + TC_GAME_API GameObjectAI* SelectGameObjectAI(GameObject*); } #endif diff --git a/src/server/game/AI/PlayerAI/PlayerAI.cpp b/src/server/game/AI/PlayerAI/PlayerAI.cpp new file mode 100644 index 00000000000..d5c17cce3ad --- /dev/null +++ b/src/server/game/AI/PlayerAI/PlayerAI.cpp @@ -0,0 +1,1367 @@ +/* + * Copyright (C) 2016-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "PlayerAI.h" +#include "SpellAuras.h" +#include "SpellAuraEffects.h" + +static const uint8 NUM_TALENT_TREES = 3; +static const uint8 NUM_SPEC_ICONICS = 3; + +enum Specs +{ + SPEC_WARRIOR_ARMS = 0, + SPEC_WARRIOR_FURY = 1, + SPEC_WARRIOR_PROTECTION = 2, + + SPEC_PALADIN_HOLY = 0, + SPEC_PALADIN_PROTECTION = 1, + SPEC_PALADIN_RETRIBUTION = 2, + + SPEC_HUNTER_BEAST_MASTERY = 0, + SPEC_HUNTER_MARKSMANSHIP = 1, + SPEC_HUNTER_SURVIVAL = 2, + + SPEC_ROGUE_ASSASSINATION = 0, + SPEC_ROGUE_COMBAT = 1, + SPEC_ROGUE_SUBLETY = 2, + + SPEC_PRIEST_DISCIPLINE = 0, + SPEC_PRIEST_HOLY = 1, + SPEC_PRIEST_SHADOW = 2, + + SPEC_DEATH_KNIGHT_BLOOD = 0, + SPEC_DEATH_KNIGHT_FROST = 1, + SPEC_DEATH_KNIGHT_UNHOLY = 2, + + SPEC_SHAMAN_ELEMENTAL = 0, + SPEC_SHAMAN_ENHANCEMENT = 1, + SPEC_SHAMAN_RESTORATION = 2, + + SPEC_MAGE_ARCANE = 0, + SPEC_MAGE_FIRE = 1, + SPEC_MAGE_FROST = 2, + + SPEC_WARLOCK_AFFLICTION = 0, + SPEC_WARLOCK_DEMONOLOGY = 1, + SPEC_WARLOCK_DESTRUCTION = 2, + + SPEC_DRUID_BALANCE = 0, + SPEC_DRUID_FERAL = 1, + SPEC_DRUID_RESTORATION = 2 +}; +enum Spells +{ + /* Generic */ + SPELL_AUTO_SHOT = 75, + SPELL_SHOOT = 3018, + SPELL_THROW = 2764, + SPELL_SHOOT_WAND = 5019, + + /* Warrior - Generic */ + SPELL_BATTLE_STANCE = 2457, + SPELL_BERSERKER_STANCE = 2458, + SPELL_DEFENSIVE_STANCE = 71, + SPELL_CHARGE = 11578, + SPELL_INTERCEPT = 20252, + SPELL_ENRAGED_REGEN = 55694, + SPELL_INTIMIDATING_SHOUT= 5246, + SPELL_PUMMEL = 6552, + SPELL_SHIELD_BASH = 72, + SPELL_BLOODRAGE = 2687, + + /* Warrior - Arms */ + SPELL_SWEEPING_STRIKES = 12328, + SPELL_MORTAL_STRIKE = 12294, + SPELL_BLADESTORM = 46924, + SPELL_REND = 47465, + SPELL_RETALIATION = 20230, + SPELL_SHATTERING_THROW = 64382, + SPELL_THUNDER_CLAP = 47502, + + /* Warrior - Fury */ + SPELL_DEATH_WISH = 12292, + SPELL_BLOODTHIRST = 23881, + PASSIVE_TITANS_GRIP = 46917, + SPELL_DEMO_SHOUT = 47437, + SPELL_EXECUTE = 47471, + SPELL_HEROIC_FURY = 60970, + SPELL_RECKLESSNESS = 1719, + SPELL_PIERCING_HOWL = 12323, + + /* Warrior - Protection */ + SPELL_VIGILANCE = 50720, + SPELL_DEVASTATE = 20243, + SPELL_SHOCKWAVE = 46968, + SPELL_CONCUSSION_BLOW = 12809, + SPELL_DISARM = 676, + SPELL_LAST_STAND = 12975, + SPELL_SHIELD_BLOCK = 2565, + SPELL_SHIELD_SLAM = 47488, + SPELL_SHIELD_WALL = 871, + SPELL_SPELL_REFLECTION = 23920, + + /* Paladin - Generic */ + SPELL_AURA_MASTERY = 31821, + SPELL_LAY_ON_HANDS = 48788, + SPELL_BLESSING_OF_MIGHT = 48932, + SPELL_AVENGING_WRATH = 31884, + SPELL_DIVINE_PROTECTION = 498, + SPELL_DIVINE_SHIELD = 642, + SPELL_HAMMER_OF_JUSTICE = 10308, + SPELL_HAND_OF_FREEDOM = 1044, + SPELL_HAND_OF_PROTECTION = 10278, + SPELL_HAND_OF_SACRIFICE = 6940, + + /* Paladin - Holy*/ + PASSIVE_ILLUMINATION = 20215, + SPELL_HOLY_SHOCK = 20473, + SPELL_BEACON_OF_LIGHT = 53563, + SPELL_CONSECRATION = 48819, + SPELL_FLASH_OF_LIGHT = 48785, + SPELL_HOLY_LIGHT = 48782, + SPELL_DIVINE_FAVOR = 20216, + SPELL_DIVINE_ILLUMINATION = 31842, + + /* Paladin - Protection */ + SPELL_BLESS_OF_SANC = 20911, + SPELL_HOLY_SHIELD = 20925, + SPELL_AVENGERS_SHIELD = 48827, + SPELL_DIVINE_SACRIFICE = 64205, + SPELL_HAMMER_OF_RIGHTEOUS = 53595, + SPELL_RIGHTEOUS_FURY = 25780, + SPELL_SHIELD_OF_RIGHTEOUS = 61411, + + /* Paladin - Retribution */ + SPELL_SEAL_OF_COMMAND = 20375, + SPELL_CRUSADER_STRIKE = 35395, + SPELL_DIVINE_STORM = 53385, + SPELL_JUDGEMENT = 20271, + SPELL_HAMMER_OF_WRATH = 48806, + + /* Hunter - Generic */ + SPELL_DETERRENCE = 19263, + SPELL_EXPLOSIVE_TRAP = 49067, + SPELL_FREEZING_ARROW = 60192, + SPELL_RAPID_FIRE = 3045, + SPELL_KILL_SHOT = 61006, + SPELL_MULTI_SHOT = 49048, + SPELL_VIPER_STING = 3034, + + /* Hunter - Beast Mastery */ + SPELL_BESTIAL_WRATH = 19574, + PASSIVE_BEAST_WITHIN = 34692, + PASSIVE_BEAST_MASTERY = 53270, + + /* Hunter - Marksmanship */ + SPELL_AIMED_SHOT = 19434, + PASSIVE_TRUESHOT_AURA = 19506, + SPELL_CHIMERA_SHOT = 53209, + SPELL_ARCANE_SHOT = 49045, + SPELL_STEADY_SHOT = 49052, + SPELL_READINESS = 23989, + SPELL_SILENCING_SHOT = 34490, + + /* Hunter - Survival */ + PASSIVE_LOCK_AND_LOAD = 56344, + SPELL_WYVERN_STING = 19386, + SPELL_EXPLOSIVE_SHOT = 53301, + SPELL_BLACK_ARROW = 3674, + + /* Rogue - Generic */ + SPELL_DISMANTLE = 51722, + SPELL_EVASION = 26669, + SPELL_KICK = 1766, + SPELL_VANISH = 26889, + SPELL_BLIND = 2094, + SPELL_CLOAK_OF_SHADOWS = 31224, + + /* Rogue - Assassination */ + SPELL_COLD_BLOOD = 14177, + SPELL_MUTILATE = 1329, + SPELL_HUNGER_FOR_BLOOD = 51662, + SPELL_ENVENOM = 57993, + + /* Rogue - Combat */ + SPELL_SINISTER_STRIKE = 48637, + SPELL_BLADE_FLURRY = 13877, + SPELL_ADRENALINE_RUSH = 13750, + SPELL_KILLING_SPREE = 51690, + SPELL_EVISCERATE = 48668, + + /* Rogue - Sublety */ + SPELL_HEMORRHAGE = 16511, + SPELL_PREMEDITATION = 14183, + SPELL_SHADOW_DANCE = 51713, + SPELL_PREPARATION = 14185, + SPELL_SHADOWSTEP = 36554, + + /* Priest - Generic */ + SPELL_FEAR_WARD = 6346, + SPELL_POWER_WORD_FORT = 48161, + SPELL_DIVINE_SPIRIT = 48073, + SPELL_SHADOW_PROTECTION = 48169, + SPELL_DIVINE_HYMN = 64843, + SPELL_HYMN_OF_HOPE = 64901, + SPELL_SHADOW_WORD_DEATH = 48158, + SPELL_PSYCHIC_SCREAM = 10890, + + /* Priest - Discipline */ + PASSIVE_SOUL_WARDING = 63574, + SPELL_POWER_INFUSION = 10060, + SPELL_PENANCE = 47540, + SPELL_PAIN_SUPPRESSION = 33206, + SPELL_INNER_FOCUS = 14751, + SPELL_POWER_WORD_SHIELD = 48066, + + /* Priest - Holy */ + PASSIVE_SPIRIT_REDEMPTION = 20711, + SPELL_DESPERATE_PRAYER = 19236, + SPELL_GUARDIAN_SPIRIT = 47788, + SPELL_FLASH_HEAL = 48071, + SPELL_RENEW = 48068, + + /* Priest - Shadow */ + SPELL_VAMPIRIC_EMBRACE = 15286, + SPELL_SHADOWFORM = 15473, + SPELL_VAMPIRIC_TOUCH = 34914, + SPELL_MIND_FLAY = 15407, + SPELL_MIND_BLAST = 48127, + SPELL_SHADOW_WORD_PAIN = 48125, + SPELL_DEVOURING_PLAGUE = 48300, + SPELL_DISPERSION = 47585, + + /* Death Knight - Generic */ + SPELL_DEATH_GRIP = 49576, + SPELL_STRANGULATE = 47476, + SPELL_EMPOWER_RUNE_WEAP = 47568, + SPELL_ICEBORN_FORTITUDE = 48792, + SPELL_ANTI_MAGIC_SHELL = 48707, + SPELL_DEATH_COIL_DK = 49895, + SPELL_MIND_FREEZE = 47528, + SPELL_ICY_TOUCH = 49909, + AURA_FROST_FEVER = 55095, + SPELL_PLAGUE_STRIKE = 49921, + AURA_BLOOD_PLAGUE = 55078, + SPELL_PESTILENCE = 50842, + + /* Death Knight - Blood */ + SPELL_RUNE_TAP = 48982, + SPELL_HYSTERIA = 49016, + SPELL_HEART_STRIKE = 55050, + SPELL_DEATH_STRIKE = 49924, + SPELL_BLOOD_STRIKE = 49930, + SPELL_MARK_OF_BLOOD = 49005, + SPELL_VAMPIRIC_BLOOD = 55233, + + /* Death Knight - Frost */ + PASSIVE_ICY_TALONS = 50887, + SPELL_FROST_STRIKE = 49143, + SPELL_HOWLING_BLAST = 49184, + SPELL_UNBREAKABLE_ARMOR = 51271, + SPELL_OBLITERATE = 51425, + SPELL_DEATHCHILL = 49796, + + /* Death Knight - Unholy */ + PASSIVE_UNHOLY_BLIGHT = 49194, + PASSIVE_MASTER_OF_GHOUL = 52143, + SPELL_SCOURGE_STRIKE = 55090, + SPELL_DEATH_AND_DECAY = 49938, + SPELL_ANTI_MAGIC_ZONE = 51052, + SPELL_SUMMON_GARGOYLE = 49206, + + /* Shaman - Generic */ + SPELL_HEROISM = 32182, + SPELL_BLOODLUST = 2825, + SPELL_GROUNDING_TOTEM = 8177, + + /* Shaman - Elemental*/ + PASSIVE_ELEMENTAL_FOCUS = 16164, + SPELL_TOTEM_OF_WRATH = 30706, + SPELL_THUNDERSTORM = 51490, + SPELL_LIGHTNING_BOLT = 49238, + SPELL_EARTH_SHOCK = 49231, + SPELL_FLAME_SHOCK = 49233, + SPELL_LAVA_BURST = 60043, + SPELL_CHAIN_LIGHTNING = 49271, + SPELL_ELEMENTAL_MASTERY = 16166, + + /* Shaman - Enhancement */ + PASSIVE_SPIRIT_WEAPONS = 16268, + SPELL_LAVA_LASH = 60103, + SPELL_FERAL_SPIRIT = 51533, + AURA_MAELSTROM_WEAPON = 53817, + SPELL_STORMSTRIKE = 17364, + SPELL_SHAMANISTIC_RAGE = 30823, + + /* Shaman - Restoration*/ + SPELL_SHA_NATURE_SWIFT = 591, + SPELL_MANA_TIDE_TOTEM = 590, + SPELL_EARTH_SHIELD = 49284, + SPELL_RIPTIDE = 61295, + SPELL_HEALING_WAVE = 49273, + SPELL_LESSER_HEAL_WAVE = 49276, + SPELL_TIDAL_FORCE = 55198, + + /* Mage - Generic */ + SPELL_DAMPEN_MAGIC = 43015, + SPELL_EVOCATION = 12051, + SPELL_MANA_SHIELD = 43020, + SPELL_MIRROR_IMAGE = 55342, + SPELL_SPELLSTEAL = 30449, + SPELL_COUNTERSPELL = 2139, + SPELL_ICE_BLOCK = 45438, + + /* Mage - Arcane */ + SPELL_FOCUS_MAGIC = 54646, + SPELL_ARCANE_POWER = 12042, + SPELL_ARCANE_BARRAGE = 44425, + SPELL_ARCANE_BLAST = 42897, + AURA_ARCANE_BLAST = 36032, + SPELL_ARCANE_MISSILES = 42846, + SPELL_PRESENCE_OF_MIND = 12043, + + /* Mage - Fire */ + SPELL_PYROBLAST = 11366, + SPELL_COMBUSTION = 11129, + SPELL_LIVING_BOMB = 44457, + SPELL_FIREBALL = 42833, + SPELL_FIRE_BLAST = 42873, + SPELL_DRAGONS_BREATH = 31661, + SPELL_BLAST_WAVE = 11113, + + /* Mage - Frost */ + SPELL_ICY_VEINS = 12472, + SPELL_ICE_BARRIER = 11426, + SPELL_DEEP_FREEZE = 44572, + SPELL_FROST_NOVA = 42917, + SPELL_FROSTBOLT = 42842, + SPELL_COLD_SNAP = 11958, + SPELL_ICE_LANCE = 42914, + + /* Warlock - Generic */ + SPELL_FEAR = 6215, + SPELL_HOWL_OF_TERROR = 17928, + SPELL_CORRUPTION = 47813, + SPELL_DEATH_COIL_W = 47860, + SPELL_SHADOW_BOLT = 47809, + SPELL_INCINERATE = 47838, + SPELL_IMMOLATE = 47811, + SPELL_SEED_OF_CORRUPTION = 47836, + + /* Warlock - Affliction */ + PASSIVE_SIPHON_LIFE = 63108, + SPELL_UNSTABLE_AFFLICTION = 30108, + SPELL_HAUNT = 48181, + SPELL_CURSE_OF_AGONY = 47864, + SPELL_DRAIN_SOUL = 47855, + + /* Warlock - Demonology */ + SPELL_SOUL_LINK = 19028, + SPELL_DEMONIC_EMPOWERMENT = 47193, + SPELL_METAMORPHOSIS = 59672, + SPELL_IMMOLATION_AURA = 50589, + SPELL_DEMON_CHARGE = 54785, + AURA_DECIMATION = 63167, + AURA_MOLTEN_CORE = 71165, + SPELL_SOUL_FIRE = 47825, + + /* Warlock - Destruction */ + SPELL_SHADOWBURN = 17877, + SPELL_CONFLAGRATE = 17962, + SPELL_CHAOS_BOLT = 50796, + SPELL_SHADOWFURY = 47847, + + /* Druid - Generic */ + SPELL_BARKSKIN = 22812, + SPELL_INNERVATE = 29166, + + /* Druid - Balance */ + SPELL_INSECT_SWARM = 5570, + SPELL_MOONKIN_FORM = 24858, + SPELL_STARFALL = 48505, + SPELL_TYPHOON = 61384, + AURA_ECLIPSE_LUNAR = 48518, + SPELL_MOONFIRE = 48463, + SPELL_STARFIRE = 48465, + SPELL_WRATH = 48461, + + /* Druid - Feral */ + SPELL_CAT_FORM = 768, + SPELL_SURVIVAL_INSTINCTS = 61336, + SPELL_MANGLE = 33917, + SPELL_BERSERK = 50334, + SPELL_MANGLE_CAT = 48566, + SPELL_FERAL_CHARGE_CAT = 49376, + SPELL_RAKE = 48574, + SPELL_RIP = 49800, + SPELL_SAVAGE_ROAR = 52610, + SPELL_TIGER_FURY = 50213, + SPELL_CLAW = 48570, + SPELL_DASH = 33357, + SPELL_MAIM = 49802, + + /* Druid - Restoration */ + SPELL_SWIFTMEND = 18562, + SPELL_TREE_OF_LIFE = 33891, + SPELL_WILD_GROWTH = 48438, + SPELL_NATURE_SWIFTNESS = 17116, + SPELL_TRANQUILITY = 48447, + SPELL_NOURISH = 50464, + SPELL_HEALING_TOUCH = 48378, + SPELL_REJUVENATION = 48441, + SPELL_REGROWTH = 48443, + SPELL_LIFEBLOOM = 48451 +}; + +// As it turns out, finding out "how many points does the player have in spec X" is actually really expensive to do frequently +// So instead, we just check for a handful of spells that, realistically, no spec is gonna go without (and "has spell" is cheap!) +// Can players deliberately trick this check? Yes. +// Is it worth doing? No. +// Close enough. +static const uint32 SPEC_ICONICS[MAX_CLASSES][NUM_TALENT_TREES][NUM_SPEC_ICONICS] = { + { // CLASS_NONE + {0,0,0}, + {0,0,0}, + {0,0,0} + }, + { // CLASS_WARRIOR + {SPELL_BLADESTORM, SPELL_MORTAL_STRIKE, SPELL_SWEEPING_STRIKES}, // Arms + {PASSIVE_TITANS_GRIP, SPELL_BLOODTHIRST, SPELL_DEATH_WISH}, // Fury + {SPELL_SHOCKWAVE, SPELL_DEVASTATE, SPELL_VIGILANCE} // Protection + }, + { // CLASS_PALADIN + {SPELL_BEACON_OF_LIGHT, SPELL_HOLY_SHOCK, PASSIVE_ILLUMINATION}, // Holy + {SPELL_HAMMER_OF_RIGHTEOUS, SPELL_HOLY_SHIELD, SPELL_BLESS_OF_SANC}, // Protection + {SPELL_DIVINE_STORM, SPELL_CRUSADER_STRIKE, SPELL_SEAL_OF_COMMAND} // Retribution + }, + { // CLASS_HUNTER + {PASSIVE_BEAST_MASTERY, PASSIVE_BEAST_WITHIN, SPELL_BESTIAL_WRATH}, // Beast Mastery + {SPELL_CHIMERA_SHOT, PASSIVE_TRUESHOT_AURA, SPELL_AIMED_SHOT}, // Marksmanship + {SPELL_EXPLOSIVE_SHOT, SPELL_WYVERN_STING, PASSIVE_LOCK_AND_LOAD} // Survival + }, + { // CLASS_ROGUE + {SPELL_HUNGER_FOR_BLOOD, SPELL_MUTILATE, SPELL_COLD_BLOOD}, // Assassination + {SPELL_KILLING_SPREE, SPELL_ADRENALINE_RUSH, SPELL_BLADE_FLURRY}, // Combat + {SPELL_SHADOW_DANCE, SPELL_PREMEDITATION, SPELL_HEMORRHAGE} // Sublety + }, + { // CLASS_PRIEST + {SPELL_PENANCE, SPELL_POWER_INFUSION, PASSIVE_SOUL_WARDING}, // Discipline + {SPELL_GUARDIAN_SPIRIT, PASSIVE_SPIRIT_REDEMPTION, SPELL_DESPERATE_PRAYER}, // Holy + {SPELL_VAMPIRIC_TOUCH, SPELL_SHADOWFORM, SPELL_VAMPIRIC_EMBRACE} // Shadow + }, + { // CLASS_DEATH_KNIGHT + {SPELL_HEART_STRIKE, SPELL_HYSTERIA, SPELL_RUNE_TAP}, // Blood + {SPELL_HOWLING_BLAST, SPELL_FROST_STRIKE, PASSIVE_ICY_TALONS}, // Frost + {SPELL_SCOURGE_STRIKE, PASSIVE_MASTER_OF_GHOUL, PASSIVE_UNHOLY_BLIGHT} // Unholy + }, + { // CLASS_SHAMAN + {SPELL_THUNDERSTORM, SPELL_TOTEM_OF_WRATH, PASSIVE_ELEMENTAL_FOCUS}, // Elemental + {SPELL_FERAL_SPIRIT, SPELL_LAVA_LASH, PASSIVE_SPIRIT_WEAPONS}, // Enhancement + {SPELL_RIPTIDE, SPELL_MANA_TIDE_TOTEM, SPELL_SHA_NATURE_SWIFT} // Restoration + }, + { // CLASS_MAGE + {SPELL_ARCANE_BARRAGE, SPELL_ARCANE_POWER, SPELL_FOCUS_MAGIC}, // Arcane + {SPELL_LIVING_BOMB, SPELL_COMBUSTION, SPELL_PYROBLAST}, // Fire + {SPELL_DEEP_FREEZE, SPELL_ICE_BARRIER, SPELL_ICY_VEINS} // Frost + }, + { // CLASS_WARLOCK + {SPELL_HAUNT, SPELL_UNSTABLE_AFFLICTION, PASSIVE_SIPHON_LIFE}, // Affliction + {SPELL_METAMORPHOSIS, SPELL_DEMONIC_EMPOWERMENT, SPELL_SOUL_LINK}, // Demonology + {SPELL_CHAOS_BOLT, SPELL_CONFLAGRATE, SPELL_SHADOWBURN} // Destruction + }, + { // CLASS_UNK + {0,0,0}, + {0,0,0}, + {0,0,0} + }, + { // CLASS_DRUID + {SPELL_STARFALL, SPELL_MOONKIN_FORM, SPELL_INSECT_SWARM}, // Balance + {SPELL_BERSERK, SPELL_MANGLE, SPELL_SURVIVAL_INSTINCTS}, // Feral + {SPELL_WILD_GROWTH, SPELL_TREE_OF_LIFE, SPELL_SWIFTMEND} // Restoration + } +}; + +uint8 PlayerAI::GetPlayerSpec(Player const* who) +{ + if (!who) + return 0; + + uint8 wClass = who->getClass(); + for (uint8 tier = 0; tier < NUM_SPEC_ICONICS; ++tier) + for (uint8 tree = 0; tree < NUM_TALENT_TREES; ++tree) + if (SPEC_ICONICS[wClass][tree][tier] && who->HasSpell(SPEC_ICONICS[wClass][tree][tier])) + return tree; + + return 0; +} + +bool PlayerAI::IsPlayerHealer(Player const* who) +{ + if (!who) + return false; + + switch (who->getClass()) + { + case CLASS_WARRIOR: + case CLASS_HUNTER: + case CLASS_ROGUE: + case CLASS_DEATH_KNIGHT: + case CLASS_MAGE: + case CLASS_WARLOCK: + default: + return false; + case CLASS_PALADIN: + return (PlayerAI::GetPlayerSpec(who) == SPEC_PALADIN_HOLY); + case CLASS_PRIEST: + return (PlayerAI::GetPlayerSpec(who) != SPEC_PRIEST_SHADOW); + case CLASS_SHAMAN: + return (PlayerAI::GetPlayerSpec(who) == SPEC_SHAMAN_RESTORATION); + case CLASS_DRUID: + return (PlayerAI::GetPlayerSpec(who) == SPEC_DRUID_RESTORATION); + } +} + +bool PlayerAI::IsPlayerRangedAttacker(Player const* who) +{ + if (!who) + return false; + + switch (who->getClass()) + { + case CLASS_WARRIOR: + case CLASS_PALADIN: + case CLASS_ROGUE: + case CLASS_DEATH_KNIGHT: + default: + return false; + case CLASS_MAGE: + case CLASS_WARLOCK: + return true; + case CLASS_HUNTER: + { + // check if we have a ranged weapon equipped + Item const* rangedSlot = who->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + if (ItemTemplate const* rangedTemplate = rangedSlot ? rangedSlot->GetTemplate() : nullptr) + if ((1 << rangedTemplate->SubClass) & ITEM_SUBCLASS_MASK_WEAPON_RANGED) + return true; + return false; + } + case CLASS_PRIEST: + return (PlayerAI::GetPlayerSpec(who) == SPEC_PRIEST_SHADOW); + case CLASS_SHAMAN: + return (PlayerAI::GetPlayerSpec(who) == SPEC_SHAMAN_ELEMENTAL); + case CLASS_DRUID: + return (PlayerAI::GetPlayerSpec(who) == SPEC_DRUID_BALANCE); + } +} + +PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, Unit* target) +{ + // Find highest spell rank that we know + uint32 knownRank, nextRank; + if (me->HasSpell(spellId)) + { + // this will save us some lookups if the player has the highest rank (expected case) + knownRank = spellId; + nextRank = sSpellMgr->GetNextSpellInChain(spellId); + } + else + { + knownRank = 0; + nextRank = sSpellMgr->GetFirstSpellInChain(spellId); + } + + while (nextRank && me->HasSpell(nextRank)) + { + knownRank = nextRank; + nextRank = sSpellMgr->GetNextSpellInChain(knownRank); + } + + if (!knownRank) + return {}; + + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(knownRank); + if (!spellInfo) + return {}; + + if (me->GetSpellHistory()->HasGlobalCooldown(spellInfo)) + return {}; + + Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE); + if (spell->CanAutoCast(target)) + return{ spell, target }; + + delete spell; + return {}; +} + +PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, SpellTarget target) +{ + Unit* pTarget = nullptr; + switch (target) + { + case TARGET_NONE: + break; + case TARGET_VICTIM: + pTarget = me->GetVictim(); + if (!pTarget) + return {}; + break; + case TARGET_CHARMER: + pTarget = me->GetCharmer(); + if (!pTarget) + return {}; + break; + case TARGET_SELF: + pTarget = me; + break; + } + + return VerifySpellCast(spellId, pTarget); +} + +PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) +{ + uint32 totalWeights = 0; + for (PossibleSpell const& wSpell : spells) + totalWeights += wSpell.second; + + TargetedSpell selected; + uint32 randNum = urand(0, totalWeights - 1); + for (PossibleSpell const& wSpell : spells) + { + if (selected) + { + delete wSpell.first.first; + continue; + } + + if (randNum < wSpell.second) + selected = wSpell.first; + else + { + randNum -= wSpell.second; + delete wSpell.first.first; + } + } + + spells.clear(); + return selected; +} + +void PlayerAI::DoRangedAttackIfReady() +{ + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + if (!me->isAttackReady(RANGED_ATTACK)) + return; + + Unit* victim = me->GetVictim(); + if (!victim) + return; + + uint32 rangedAttackSpell = 0; + + Item const* rangedItem = me->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + if (ItemTemplate const* rangedTemplate = rangedItem ? rangedItem->GetTemplate() : nullptr) + { + switch (rangedTemplate->SubClass) + { + case ITEM_SUBCLASS_WEAPON_BOW: + case ITEM_SUBCLASS_WEAPON_GUN: + case ITEM_SUBCLASS_WEAPON_CROSSBOW: + rangedAttackSpell = SPELL_SHOOT; + break; + case ITEM_SUBCLASS_WEAPON_THROWN: + rangedAttackSpell = SPELL_THROW; + break; + case ITEM_SUBCLASS_WEAPON_WAND: + rangedAttackSpell = SPELL_SHOOT_WAND; + break; + } + } + + if (!rangedAttackSpell) + return; + + me->CastSpell(victim, rangedAttackSpell, TRIGGERED_CAST_DIRECTLY); + me->resetAttackTimer(RANGED_ATTACK); +} + +void PlayerAI::DoAutoAttackIfReady() +{ + if (IsRangedAttacker()) + DoRangedAttackIfReady(); + else + DoMeleeAttackIfReady(); +} + +void PlayerAI::CancelAllShapeshifts() +{ + std::list<AuraEffect*> const& shapeshiftAuras = me->GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT); + std::set<Aura*> removableShapeshifts; + for (AuraEffect* auraEff : shapeshiftAuras) + { + Aura* aura = auraEff->GetBase(); + if (!aura) + continue; + SpellInfo const* auraInfo = aura->GetSpellInfo(); + if (!auraInfo) + continue; + if (auraInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL)) + continue; + if (!auraInfo->IsPositive() || auraInfo->IsPassive()) + continue; + removableShapeshifts.insert(aura); + } + + for (Aura* aura : removableShapeshifts) + me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); +} + +struct UncontrolledTargetSelectPredicate : public std::unary_function<Unit*, bool> +{ + bool operator()(Unit const* target) const + { + return !target->HasBreakableByDamageCrowdControlAura(); + } +}; +Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const +{ + if (Unit* charmer = me->GetCharmer()) + return charmer->IsAIEnabled ? charmer->GetAI()->SelectTarget(SELECT_TARGET_RANDOM, 0, UncontrolledTargetSelectPredicate()) : charmer->GetVictim(); + return nullptr; +} + +PlayerAI::TargetedSpell SimpleCharmedPlayerAI::SelectAppropriateCastForSpec() +{ + PossibleSpellVector spells; + + switch (me->getClass()) + { + case CLASS_WARRIOR: + if (!me->IsWithinMeleeRange(me->GetVictim())) + { + VerifyAndPushSpellCast(spells, SPELL_CHARGE, TARGET_VICTIM, 15); + VerifyAndPushSpellCast(spells, SPELL_INTERCEPT, TARGET_VICTIM, 10); + } + VerifyAndPushSpellCast(spells, SPELL_ENRAGED_REGEN, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_INTIMIDATING_SHOUT, TARGET_VICTIM, 4); + if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) + { + VerifyAndPushSpellCast(spells, SPELL_PUMMEL, TARGET_VICTIM, 15); + VerifyAndPushSpellCast(spells, SPELL_SHIELD_BASH, TARGET_VICTIM, 15); + } + VerifyAndPushSpellCast(spells, SPELL_BLOODRAGE, TARGET_NONE, 5); + switch (GetSpec()) + { + case SPEC_WARRIOR_PROTECTION: + VerifyAndPushSpellCast(spells, SPELL_SHOCKWAVE, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_CONCUSSION_BLOW, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_DISARM, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_LAST_STAND, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_SHIELD_BLOCK, TARGET_NONE, 1); + VerifyAndPushSpellCast(spells, SPELL_SHIELD_SLAM, TARGET_VICTIM, 4); + VerifyAndPushSpellCast(spells, SPELL_SHIELD_WALL, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_SPELL_REFLECTION, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_DEVASTATE, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 1); + break; + case SPEC_WARRIOR_ARMS: + VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 2); + VerifyAndPushSpellCast(spells, SPELL_MORTAL_STRIKE, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_BLADESTORM, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_RETALIATION, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_SHATTERING_THROW, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); + break; + case SPEC_WARRIOR_FURY: + VerifyAndPushSpellCast(spells, SPELL_DEATH_WISH, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_BLOODTHIRST, TARGET_VICTIM, 4); + VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); + VerifyAndPushSpellCast(spells, SPELL_HEROIC_FURY, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_RECKLESSNESS, TARGET_NONE, 8); + VerifyAndPushSpellCast(spells, SPELL_PIERCING_HOWL, TARGET_VICTIM, 2); + break; + } + break; + case CLASS_PALADIN: + VerifyAndPushSpellCast(spells, SPELL_AURA_MASTERY, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_LAY_ON_HANDS, TARGET_CHARMER, 8); + VerifyAndPushSpellCast(spells, SPELL_BLESSING_OF_MIGHT, TARGET_CHARMER, 8); + VerifyAndPushSpellCast(spells, SPELL_AVENGING_WRATH, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_PROTECTION, TARGET_NONE, 4); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_SHIELD, TARGET_NONE, 2); + VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_JUSTICE, TARGET_VICTIM, 6); + VerifyAndPushSpellCast(spells, SPELL_HAND_OF_FREEDOM, TARGET_SELF, 3); + VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, TARGET_SELF, 1); + if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) + { + if (creatureCharmer->IsDungeonBoss() || creatureCharmer->isWorldBoss()) + VerifyAndPushSpellCast(spells, SPELL_HAND_OF_SACRIFICE, creatureCharmer, 10); + else + VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, creatureCharmer, 3); + } + + switch (GetSpec()) + { + case SPEC_PALADIN_PROTECTION: + VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_RIGHTEOUS, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_SACRIFICE, TARGET_NONE, 2); + VerifyAndPushSpellCast(spells, SPELL_SHIELD_OF_RIGHTEOUS, TARGET_VICTIM, 4); + VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_CONSECRATION, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_HOLY_SHIELD, TARGET_NONE, 1); + break; + case SPEC_PALADIN_HOLY: + VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_CHARMER, 3); + VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_FLASH_OF_LIGHT, TARGET_CHARMER, 4); + VerifyAndPushSpellCast(spells, SPELL_HOLY_LIGHT, TARGET_CHARMER, 3); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_FAVOR, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_ILLUMINATION, TARGET_NONE, 3); + break; + case SPEC_PALADIN_RETRIBUTION: + VerifyAndPushSpellCast(spells, SPELL_CRUSADER_STRIKE, TARGET_VICTIM, 4); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_STORM, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_WRATH, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_RIGHTEOUS_FURY, TARGET_NONE, 2); + break; + } + break; + case CLASS_HUNTER: + VerifyAndPushSpellCast(spells, SPELL_DETERRENCE, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_TRAP, TARGET_NONE, 1); + VerifyAndPushSpellCast(spells, SPELL_FREEZING_ARROW, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_RAPID_FIRE, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_KILL_SHOT, TARGET_VICTIM, 10); + if (me->GetVictim() && me->GetVictim()->getPowerType() == POWER_MANA && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_VIPER_STING, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_VIPER_STING, TARGET_VICTIM, 5); + + switch (GetSpec()) + { + case SPEC_HUNTER_BEAST_MASTERY: + VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 2); + break; + case SPEC_HUNTER_MARKSMANSHIP: + VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_CHIMERA_SHOT, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_READINESS, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_SILENCING_SHOT, TARGET_VICTIM, 5); + break; + case SPEC_HUNTER_SURVIVAL: + VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_SHOT, TARGET_VICTIM, 8); + VerifyAndPushSpellCast(spells, SPELL_BLACK_ARROW, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 1); + break; + } + break; + case CLASS_ROGUE: + { + VerifyAndPushSpellCast(spells, SPELL_DISMANTLE, TARGET_VICTIM, 8); + VerifyAndPushSpellCast(spells, SPELL_EVASION, TARGET_NONE, 8); + VerifyAndPushSpellCast(spells, SPELL_VANISH, TARGET_NONE, 4); + VerifyAndPushSpellCast(spells, SPELL_BLIND, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_CLOAK_OF_SHADOWS, TARGET_NONE, 2); + + uint32 builder = 0, finisher = 0; + switch (GetSpec()) + { + case SPEC_ROGUE_ASSASSINATION: + builder = SPELL_MUTILATE, finisher = SPELL_ENVENOM; + VerifyAndPushSpellCast(spells, SPELL_COLD_BLOOD, TARGET_NONE, 20); + break; + case SPEC_ROGUE_COMBAT: + builder = SPELL_SINISTER_STRIKE, finisher = SPELL_EVISCERATE; + VerifyAndPushSpellCast(spells, SPELL_ADRENALINE_RUSH, TARGET_NONE, 6); + VerifyAndPushSpellCast(spells, SPELL_BLADE_FLURRY, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_KILLING_SPREE, TARGET_NONE, 25); + break; + case SPEC_ROGUE_SUBLETY: + builder = SPELL_HEMORRHAGE, finisher = SPELL_EVISCERATE; + VerifyAndPushSpellCast(spells, SPELL_PREPARATION, TARGET_NONE, 10); + if (!me->IsWithinMeleeRange(me->GetVictim())) + VerifyAndPushSpellCast(spells, SPELL_SHADOWSTEP, TARGET_VICTIM, 25); + VerifyAndPushSpellCast(spells, SPELL_SHADOW_DANCE, TARGET_NONE, 10); + break; + } + + if (Unit* victim = me->GetVictim()) + { + if (victim->HasUnitState(UNIT_STATE_CASTING)) + VerifyAndPushSpellCast(spells, SPELL_KICK, TARGET_VICTIM, 25); + + uint8 const cp = (me->GetComboTarget() == victim->GetGUID()) ? me->GetComboPoints() : 0; + if (cp >= 4) + VerifyAndPushSpellCast(spells, finisher, TARGET_VICTIM, 10); + if (cp <= 4) + VerifyAndPushSpellCast(spells, builder, TARGET_VICTIM, 5); + } + break; + } + case CLASS_PRIEST: + VerifyAndPushSpellCast(spells, SPELL_FEAR_WARD, TARGET_SELF, 2); + VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_FORT, TARGET_CHARMER, 1); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_SPIRIT, TARGET_CHARMER, 1); + VerifyAndPushSpellCast(spells, SPELL_SHADOW_PROTECTION, TARGET_CHARMER, 2); + VerifyAndPushSpellCast(spells, SPELL_DIVINE_HYMN, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_HYMN_OF_HOPE, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_DEATH, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_PSYCHIC_SCREAM, TARGET_VICTIM, 3); + switch (GetSpec()) + { + case SPEC_PRIEST_DISCIPLINE: + VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_SHIELD, TARGET_CHARMER, 3); + VerifyAndPushSpellCast(spells, SPELL_INNER_FOCUS, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_PAIN_SUPPRESSION, TARGET_CHARMER, 15); + VerifyAndPushSpellCast(spells, SPELL_POWER_INFUSION, TARGET_CHARMER, 10); + VerifyAndPushSpellCast(spells, SPELL_PENANCE, TARGET_CHARMER, 3); + VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); + break; + case SPEC_PRIEST_HOLY: + VerifyAndPushSpellCast(spells, SPELL_DESPERATE_PRAYER, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_GUARDIAN_SPIRIT, TARGET_CHARMER, 5); + VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); + VerifyAndPushSpellCast(spells, SPELL_RENEW, TARGET_CHARMER, 3); + break; + case SPEC_PRIEST_SHADOW: + if (!me->HasAura(SPELL_SHADOWFORM)) + { + VerifyAndPushSpellCast(spells, SPELL_SHADOWFORM, TARGET_NONE, 100); + break; + } + if (Unit* victim = me->GetVictim()) + { + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_VAMPIRIC_TOUCH, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_TOUCH, TARGET_VICTIM, 4); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_SHADOW_WORD_PAIN, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_PAIN, TARGET_VICTIM, 3); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_DEVOURING_PLAGUE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_DEVOURING_PLAGUE, TARGET_VICTIM, 4); + } + VerifyAndPushSpellCast(spells, SPELL_MIND_BLAST, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_MIND_FLAY, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_DISPERSION, TARGET_NONE, 10); + break; + } + break; + case CLASS_DEATH_KNIGHT: + { + if (!me->IsWithinMeleeRange(me->GetVictim())) + VerifyAndPushSpellCast(spells, SPELL_DEATH_GRIP, TARGET_VICTIM, 25); + VerifyAndPushSpellCast(spells, SPELL_STRANGULATE, TARGET_VICTIM, 15); + VerifyAndPushSpellCast(spells, SPELL_EMPOWER_RUNE_WEAP, TARGET_NONE, 5); + VerifyAndPushSpellCast(spells, SPELL_ICEBORN_FORTITUDE, TARGET_NONE, 15); + VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_SHELL, TARGET_NONE, 10); + + bool hasFF = false, hasBP = false; + if (Unit* victim = me->GetVictim()) + { + if (victim->HasUnitState(UNIT_STATE_CASTING)) + VerifyAndPushSpellCast(spells, SPELL_MIND_FREEZE, TARGET_VICTIM, 25); + + hasFF = !!victim->GetAuraApplicationOfRankedSpell(AURA_FROST_FEVER, me->GetGUID()), hasBP = !!victim->GetAuraApplicationOfRankedSpell(AURA_BLOOD_PLAGUE, me->GetGUID()); + if (hasFF && hasBP) + VerifyAndPushSpellCast(spells, SPELL_PESTILENCE, TARGET_VICTIM, 3); + if (!hasFF) + VerifyAndPushSpellCast(spells, SPELL_ICY_TOUCH, TARGET_VICTIM, 4); + if (!hasBP) + VerifyAndPushSpellCast(spells, SPELL_PLAGUE_STRIKE, TARGET_VICTIM, 4); + } + switch (GetSpec()) + { + case SPEC_DEATH_KNIGHT_BLOOD: + VerifyAndPushSpellCast(spells, SPELL_RUNE_TAP, TARGET_NONE, 2); + VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, TARGET_SELF, 5); + if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) + if (!creatureCharmer->IsDungeonBoss() && !creatureCharmer->isWorldBoss()) + VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, creatureCharmer, 15); + VerifyAndPushSpellCast(spells, SPELL_HEART_STRIKE, TARGET_VICTIM, 2); + if (hasFF && hasBP) + VerifyAndPushSpellCast(spells, SPELL_DEATH_STRIKE, TARGET_VICTIM, 8); + VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_MARK_OF_BLOOD, TARGET_VICTIM, 20); + VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_BLOOD, TARGET_NONE, 10); + break; + case SPEC_DEATH_KNIGHT_FROST: + if (hasFF && hasBP) + VerifyAndPushSpellCast(spells, SPELL_OBLITERATE, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_HOWLING_BLAST, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_UNBREAKABLE_ARMOR, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_DEATHCHILL, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_FROST_STRIKE, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); + break; + case SPEC_DEATH_KNIGHT_UNHOLY: + if (hasFF && hasBP) + VerifyAndPushSpellCast(spells, SPELL_SCOURGE_STRIKE, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_DEATH_AND_DECAY, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_ZONE, TARGET_NONE, 8); + VerifyAndPushSpellCast(spells, SPELL_SUMMON_GARGOYLE, TARGET_VICTIM, 7); + VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 3); + break; + } + break; + } + case CLASS_SHAMAN: + VerifyAndPushSpellCast(spells, SPELL_HEROISM, TARGET_NONE, 25); + VerifyAndPushSpellCast(spells, SPELL_BLOODLUST, TARGET_NONE, 25); + VerifyAndPushSpellCast(spells, SPELL_GROUNDING_TOTEM, TARGET_NONE, 2); + switch (GetSpec()) + { + case SPEC_SHAMAN_RESTORATION: + if (Unit* charmer = me->GetCharmer()) + if (!charmer->GetAuraApplicationOfRankedSpell(SPELL_EARTH_SHIELD, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_EARTH_SHIELD, charmer, 2); + if (me->HasAura(SPELL_SHA_NATURE_SWIFT)) + VerifyAndPushSpellCast(spells, SPELL_HEALING_WAVE, TARGET_CHARMER, 20); + else + VerifyAndPushSpellCast(spells, SPELL_LESSER_HEAL_WAVE, TARGET_CHARMER, 1); + VerifyAndPushSpellCast(spells, SPELL_TIDAL_FORCE, TARGET_NONE, 4); + VerifyAndPushSpellCast(spells, SPELL_SHA_NATURE_SWIFT, TARGET_NONE, 4); + VerifyAndPushSpellCast(spells, SPELL_MANA_TIDE_TOTEM, TARGET_NONE, 3); + break; + case SPEC_SHAMAN_ELEMENTAL: + if (Unit* victim = me->GetVictim()) + { + if (victim->GetAuraOfRankedSpell(SPELL_FLAME_SHOCK, GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_LAVA_BURST, TARGET_VICTIM, 5); + else + VerifyAndPushSpellCast(spells, SPELL_FLAME_SHOCK, TARGET_VICTIM, 3); + } + VerifyAndPushSpellCast(spells, SPELL_CHAIN_LIGHTNING, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_ELEMENTAL_MASTERY, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_THUNDERSTORM, TARGET_NONE, 3); + break; + case SPEC_SHAMAN_ENHANCEMENT: + if (Aura const* maelstrom = me->GetAura(AURA_MAELSTROM_WEAPON)) + if (maelstrom->GetStackAmount() == 5) + VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_STORMSTRIKE, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_EARTH_SHOCK, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_LAVA_LASH, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_SHAMANISTIC_RAGE, TARGET_NONE, 10); + break; + } + break; + case CLASS_MAGE: + if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) + VerifyAndPushSpellCast(spells, SPELL_COUNTERSPELL, TARGET_VICTIM, 25); + VerifyAndPushSpellCast(spells, SPELL_DAMPEN_MAGIC, TARGET_CHARMER, 2); + VerifyAndPushSpellCast(spells, SPELL_EVOCATION, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_MANA_SHIELD, TARGET_NONE, 1); + VerifyAndPushSpellCast(spells, SPELL_MIRROR_IMAGE, TARGET_NONE, 3); + VerifyAndPushSpellCast(spells, SPELL_SPELLSTEAL, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_ICE_BLOCK, TARGET_NONE, 1); + VerifyAndPushSpellCast(spells, SPELL_ICY_VEINS, TARGET_NONE, 3); + switch (GetSpec()) + { + case SPEC_MAGE_ARCANE: + if (Aura* abAura = me->GetAura(AURA_ARCANE_BLAST)) + if (abAura->GetStackAmount() >= 3) + VerifyAndPushSpellCast(spells, SPELL_ARCANE_MISSILES, TARGET_VICTIM, 7); + VerifyAndPushSpellCast(spells, SPELL_ARCANE_BLAST, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_ARCANE_BARRAGE, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_ARCANE_POWER, TARGET_NONE, 8); + VerifyAndPushSpellCast(spells, SPELL_PRESENCE_OF_MIND, TARGET_NONE, 7); + break; + case SPEC_MAGE_FIRE: + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_LIVING_BOMB)) + VerifyAndPushSpellCast(spells, SPELL_LIVING_BOMB, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_COMBUSTION, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_FIREBALL, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_FIRE_BLAST, TARGET_VICTIM, 1); + VerifyAndPushSpellCast(spells, SPELL_DRAGONS_BREATH, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_BLAST_WAVE, TARGET_VICTIM, 1); + break; + case SPEC_MAGE_FROST: + VerifyAndPushSpellCast(spells, SPELL_DEEP_FREEZE, TARGET_VICTIM, 10); + VerifyAndPushSpellCast(spells, SPELL_FROST_NOVA, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_FROSTBOLT, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_COLD_SNAP, TARGET_VICTIM, 5); + if (me->GetVictim() && me->GetVictim()->HasAuraState(AURA_STATE_FROZEN, nullptr, me)) + VerifyAndPushSpellCast(spells, SPELL_ICE_LANCE, TARGET_VICTIM, 5); + break; + } + break; + case CLASS_WARLOCK: + VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_W, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_FEAR, TARGET_VICTIM, 2); + VerifyAndPushSpellCast(spells, SPELL_SEED_OF_CORRUPTION, TARGET_VICTIM, 4); + VerifyAndPushSpellCast(spells, SPELL_HOWL_OF_TERROR, TARGET_NONE, 2); + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_CORRUPTION, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_CORRUPTION, TARGET_VICTIM, 10); + switch (GetSpec()) + { + case SPEC_WARLOCK_AFFLICTION: + if (Unit* victim = me->GetVictim()) + { + VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_UNSTABLE_AFFLICTION, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_UNSTABLE_AFFLICTION, TARGET_VICTIM, 8); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_HAUNT, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_HAUNT, TARGET_VICTIM, 8); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_CURSE_OF_AGONY, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_CURSE_OF_AGONY, TARGET_VICTIM, 4); + if (victim->HealthBelowPct(25)) + VerifyAndPushSpellCast(spells, SPELL_DRAIN_SOUL, TARGET_VICTIM, 100); + } + break; + case SPEC_WARLOCK_DEMONOLOGY: + VerifyAndPushSpellCast(spells, SPELL_METAMORPHOSIS, TARGET_NONE, 15); + VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); + if (me->HasAura(AURA_DECIMATION)) + VerifyAndPushSpellCast(spells, SPELL_SOUL_FIRE, TARGET_VICTIM, 100); + if (me->HasAura(SPELL_METAMORPHOSIS)) + { + VerifyAndPushSpellCast(spells, SPELL_IMMOLATION_AURA, TARGET_NONE, 30); + if (!me->IsWithinMeleeRange(me->GetVictim())) + VerifyAndPushSpellCast(spells, SPELL_DEMON_CHARGE, TARGET_VICTIM, 20); + } + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 5); + if (me->HasAura(AURA_MOLTEN_CORE)) + VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 10); + break; + case SPEC_WARLOCK_DESTRUCTION: + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 8); + if (me->GetVictim() && me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_CONFLAGRATE, TARGET_VICTIM, 8); + VerifyAndPushSpellCast(spells, SPELL_SHADOWFURY, TARGET_VICTIM, 5); + VerifyAndPushSpellCast(spells, SPELL_CHAOS_BOLT, TARGET_VICTIM, 10); + VerifyAndPushSpellCast(spells, SPELL_SHADOWBURN, TARGET_VICTIM, 3); + VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 7); + break; + } + break; + case CLASS_DRUID: + VerifyAndPushSpellCast(spells, SPELL_INNERVATE, TARGET_CHARMER, 5); + VerifyAndPushSpellCast(spells, SPELL_BARKSKIN, TARGET_NONE, 5); + switch (GetSpec()) + { + case SPEC_DRUID_RESTORATION: + if (!me->HasAura(SPELL_TREE_OF_LIFE)) + { + CancelAllShapeshifts(); + VerifyAndPushSpellCast(spells, SPELL_TREE_OF_LIFE, TARGET_NONE, 100); + break; + } + VerifyAndPushSpellCast(spells, SPELL_TRANQUILITY, TARGET_NONE, 10); + VerifyAndPushSpellCast(spells, SPELL_NATURE_SWIFTNESS, TARGET_NONE, 7); + if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) + { + VerifyAndPushSpellCast(spells, SPELL_NOURISH, creatureCharmer, 5); + VerifyAndPushSpellCast(spells, SPELL_WILD_GROWTH, creatureCharmer, 5); + if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_REJUVENATION, creatureCharmer, 8); + if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_REGROWTH, creatureCharmer, 8); + uint8 lifebloomStacks = 0; + if (Aura const* lifebloom = creatureCharmer->GetAura(SPELL_LIFEBLOOM, me->GetGUID())) + lifebloomStacks = lifebloom->GetStackAmount(); + if (lifebloomStacks < 3) + VerifyAndPushSpellCast(spells, SPELL_LIFEBLOOM, creatureCharmer, 5); + if (creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION) || + creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH)) + VerifyAndPushSpellCast(spells, SPELL_SWIFTMEND, creatureCharmer, 10); + if (me->HasAura(SPELL_NATURE_SWIFTNESS)) + VerifyAndPushSpellCast(spells, SPELL_HEALING_TOUCH, creatureCharmer, 100); + } + break; + case SPEC_DRUID_BALANCE: + { + if (!me->HasAura(SPELL_MOONKIN_FORM)) + { + CancelAllShapeshifts(); + VerifyAndPushSpellCast(spells, SPELL_MOONKIN_FORM, TARGET_NONE, 100); + break; + } + uint32 const mainAttackSpell = me->HasAura(AURA_ECLIPSE_LUNAR) ? SPELL_STARFIRE : SPELL_WRATH; + VerifyAndPushSpellCast(spells, SPELL_STARFALL, TARGET_NONE, 20); + VerifyAndPushSpellCast(spells, mainAttackSpell, TARGET_VICTIM, 10); + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_INSECT_SWARM, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_INSECT_SWARM, TARGET_VICTIM, 7); + if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_MOONFIRE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_MOONFIRE, TARGET_VICTIM, 5); + if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) + VerifyAndPushSpellCast(spells, SPELL_TYPHOON, TARGET_NONE, 15); + break; + } + case SPEC_DRUID_FERAL: + if (!me->HasAura(SPELL_CAT_FORM)) + { + CancelAllShapeshifts(); + VerifyAndPushSpellCast(spells, SPELL_CAT_FORM, TARGET_NONE, 100); + break; + } + VerifyAndPushSpellCast(spells, SPELL_BERSERK, TARGET_NONE, 20); + VerifyAndPushSpellCast(spells, SPELL_SURVIVAL_INSTINCTS, TARGET_NONE, 15); + VerifyAndPushSpellCast(spells, SPELL_TIGER_FURY, TARGET_NONE, 15); + VerifyAndPushSpellCast(spells, SPELL_DASH, TARGET_NONE, 5); + if (Unit* victim = me->GetVictim()) + { + uint8 const cp = (me->GetComboTarget() == victim->GetGUID()) ? me->GetComboPoints() : 0; + if (victim->HasUnitState(UNIT_STATE_CASTING) && cp >= 1) + VerifyAndPushSpellCast(spells, SPELL_MAIM, TARGET_VICTIM, 25); + if (!me->IsWithinMeleeRange(victim)) + VerifyAndPushSpellCast(spells, SPELL_FERAL_CHARGE_CAT, TARGET_VICTIM, 25); + if (cp >= 4) + VerifyAndPushSpellCast(spells, SPELL_RIP, TARGET_VICTIM, 50); + if (cp <= 4) + { + VerifyAndPushSpellCast(spells, SPELL_MANGLE_CAT, TARGET_VICTIM, 10); + VerifyAndPushSpellCast(spells, SPELL_CLAW, TARGET_VICTIM, 5); + if (!victim->GetAuraApplicationOfRankedSpell(SPELL_RAKE, me->GetGUID())) + VerifyAndPushSpellCast(spells, SPELL_RAKE, TARGET_VICTIM, 8); + if (!me->HasAura(SPELL_SAVAGE_ROAR)) + VerifyAndPushSpellCast(spells, SPELL_SAVAGE_ROAR, TARGET_NONE, 15); + } + } + break; + } + break; + } + + return SelectSpellCast(spells); +} + +static const float CASTER_CHASE_DISTANCE = 28.0f; +void SimpleCharmedPlayerAI::UpdateAI(const uint32 diff) +{ + Creature* charmer = me->GetCharmer() ? me->GetCharmer()->ToCreature() : nullptr; + if (!charmer) + return; + + //kill self if charm aura has infinite duration + if (charmer->IsInEvadeMode()) + { + Player::AuraEffectList const& auras = me->GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); + for (Player::AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) + if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) + { + me->KillSelf(); + return; + } + } + + if (charmer->IsInCombat()) + { + Unit* target = me->GetVictim(); + if (!target || !charmer->IsValidAttackTarget(target) || target->HasBreakableByDamageCrowdControlAura()) + { + target = SelectAttackTarget(); + if (!target) + return; + + if (IsRangedAttacker()) + { + _chaseCloser = !me->IsWithinLOSInMap(target); + if (_chaseCloser) + AttackStart(target); + else + AttackStartCaster(target, CASTER_CHASE_DISTANCE); + } + else + AttackStart(target); + _forceFacing = true; + } + + if (me->IsStopped() && !me->HasUnitState(UNIT_STATE_CANNOT_TURN)) + { + float targetAngle = me->GetAngle(target); + if (_forceFacing || fabs(me->GetOrientation() - targetAngle) > 0.4f) + { + me->SetFacingTo(targetAngle); + _forceFacing = false; + } + } + + if (_castCheckTimer <= diff) + { + if (me->HasUnitState(UNIT_STATE_CASTING)) + _castCheckTimer = 0; + else + { + if (IsRangedAttacker()) + { // chase to zero if the target isn't in line of sight + bool inLOS = me->IsWithinLOSInMap(target); + if (_chaseCloser != !inLOS) + { + _chaseCloser = !inLOS; + if (_chaseCloser) + AttackStart(target); + else + AttackStartCaster(target, CASTER_CHASE_DISTANCE); + } + } + if (TargetedSpell shouldCast = SelectAppropriateCastForSpec()) + DoCastAtTarget(shouldCast); + _castCheckTimer = 500; + } + } + else + _castCheckTimer -= diff; + + DoAutoAttackIfReady(); + } + else + { + me->AttackStop(); + me->CastStop(); + me->StopMoving(); + me->GetMotionMaster()->Clear(); + me->GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); + } +} + +void SimpleCharmedPlayerAI::OnCharmed(bool apply) +{ + if (apply) + { + me->CastStop(); + me->AttackStop(); + me->StopMoving(); + me->GetMotionMaster()->Clear(); + me->GetMotionMaster()->MovePoint(0, me->GetPosition(), false); // force re-sync of current position for all clients + } + else + { + me->CastStop(); + me->AttackStop(); + // @todo only voluntary movement (don't cancel stuff like death grip or charge mid-animation) + me->GetMotionMaster()->Clear(); + me->StopMoving(); + } +} diff --git a/src/server/game/AI/PlayerAI/PlayerAI.h b/src/server/game/AI/PlayerAI/PlayerAI.h new file mode 100644 index 00000000000..18f65485161 --- /dev/null +++ b/src/server/game/AI/PlayerAI/PlayerAI.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2016-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef TRINITY_PLAYERAI_H +#define TRINITY_PLAYERAI_H + +#include "UnitAI.h" +#include "Player.h" +#include "Spell.h" +#include "Creature.h" + +class TC_GAME_API PlayerAI : public UnitAI +{ + public: + explicit PlayerAI(Player* player) : UnitAI(static_cast<Unit*>(player)), me(player), _selfSpec(PlayerAI::GetPlayerSpec(player)), _isSelfHealer(PlayerAI::IsPlayerHealer(player)), _isSelfRangedAttacker(PlayerAI::IsPlayerRangedAttacker(player)) { } + + void OnCharmed(bool /*apply*/) override { } // charm AI application for players is handled by Unit::SetCharmedBy / Unit::RemoveCharmedBy + + // helper functions to determine player info + // Return values range from 0 (left-most spec) to 2 (right-most spec). If two specs have the same number of talent points, the left-most of those specs is returned. + static uint8 GetPlayerSpec(Player const* who); + // Return values range from 0 (left-most spec) to 2 (right-most spec). If two specs have the same number of talent points, the left-most of those specs is returned. + uint8 GetSpec(Player const* who = nullptr) const { return (!who || who == me) ? _selfSpec : GetPlayerSpec(who); } + static bool IsPlayerHealer(Player const* who); + bool IsHealer(Player const* who = nullptr) const { return (!who || who == me) ? _isSelfHealer : IsPlayerHealer(who); } + static bool IsPlayerRangedAttacker(Player const* who); + bool IsRangedAttacker(Player const* who = nullptr) const { return (!who || who == me) ? _isSelfRangedAttacker : IsPlayerRangedAttacker(who); } + + protected: + struct TargetedSpell : public std::pair<Spell*, Unit*> + { + TargetedSpell() : pair<Spell*, Unit*>() { } + TargetedSpell(Spell* first, Unit* second) : pair<Spell*, Unit*>(first, second) { } + explicit operator bool() { return !!first; } + }; + typedef std::pair<TargetedSpell, uint32> PossibleSpell; + typedef std::vector<PossibleSpell> PossibleSpellVector; + + Player* const me; + void SetIsRangedAttacker(bool state) { _isSelfRangedAttacker = state; } // this allows overriding of the default ranged attacker detection + + enum SpellTarget + { + TARGET_NONE, + TARGET_VICTIM, + TARGET_CHARMER, + TARGET_SELF + }; + /* Check if the specified spell can be cast on that target. + Caller is responsible for cleaning up created Spell object from pointer. */ + TargetedSpell VerifySpellCast(uint32 spellId, Unit* target); + /* Check if the specified spell can be cast on that target. + Caller is responsible for cleaning up created Spell object from pointer. */ + TargetedSpell VerifySpellCast(uint32 spellId, SpellTarget target); + + /* Helper method - checks spell cast, then pushes it onto provided vector if valid. */ + template<typename T> inline void VerifyAndPushSpellCast(PossibleSpellVector& spells, uint32 spellId, T target, uint32 weight) + { + if (TargetedSpell spell = VerifySpellCast(spellId, target)) + spells.push_back({ spell,weight }); + } + + /* Helper method - selects one spell from the vector and returns it, while deleting everything else. + This invalidates the vector, and empties it to prevent accidental misuse. */ + TargetedSpell SelectSpellCast(PossibleSpellVector& spells); + /* Helper method - casts the included spell at the included target */ + inline void DoCastAtTarget(TargetedSpell spell) + { + SpellCastTargets targets; + targets.SetUnitTarget(spell.second); + spell.first->prepare(&targets); + } + + virtual Unit* SelectAttackTarget() const { return me->GetCharmer() ? me->GetCharmer()->GetVictim() : nullptr; } + void DoRangedAttackIfReady(); + void DoAutoAttackIfReady(); + + // Cancels all shapeshifts that the player could voluntarily cancel + void CancelAllShapeshifts(); + + private: + uint8 const _selfSpec; + bool const _isSelfHealer; + bool _isSelfRangedAttacker; +}; + +class SimpleCharmedPlayerAI : public PlayerAI +{ + public: + SimpleCharmedPlayerAI(Player* player) : PlayerAI(player), _castCheckTimer(500), _chaseCloser(false), _forceFacing(true) { } + void UpdateAI(uint32 diff) override; + void OnCharmed(bool apply) override; + + protected: + Unit* SelectAttackTarget() const override; + + private: + TargetedSpell SelectAppropriateCastForSpec(); + uint32 _castCheckTimer; + bool _chaseCloser; + bool _forceFacing; +}; + +#endif diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index 8a1be33cc2b..316a9704cac 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -32,7 +32,7 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } extern* SpellSummary; -void SummonList::DoZoneInCombat(uint32 entry) +void SummonList::DoZoneInCombat(uint32 entry, float maxRangeToNearestTarget) { for (StorageType::iterator i = storage_.begin(); i != storage_.end();) { @@ -41,7 +41,7 @@ void SummonList::DoZoneInCombat(uint32 entry) if (summon && summon->IsAIEnabled && (!entry || summon->GetEntry() == entry)) { - summon->AI()->DoZoneInCombat(); + summon->AI()->DoZoneInCombat(nullptr, maxRangeToNearestTarget); } } } @@ -183,22 +183,22 @@ SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mec { //No target so we can't cast if (!target) - return NULL; + return nullptr; //Silenced so we can't cast if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED)) - return NULL; + return nullptr; //Using the extended script system we first create a list of viable spells - SpellInfo const* apSpell[CREATURE_MAX_SPELLS]; - memset(apSpell, 0, CREATURE_MAX_SPELLS * sizeof(SpellInfo*)); + SpellInfo const* apSpell[MAX_CREATURE_SPELLS]; + memset(apSpell, 0, MAX_CREATURE_SPELLS * sizeof(SpellInfo*)); uint32 spellCount = 0; - SpellInfo const* tempSpell = NULL; + SpellInfo const* tempSpell = nullptr; //Check if each spell is viable(set it to null if not) - for (uint32 i = 0; i < CREATURE_MAX_SPELLS; i++) + for (uint32 i = 0; i < MAX_CREATURE_SPELLS; i++) { tempSpell = sSpellMgr->GetSpellInfo(me->m_spells[i]); @@ -251,7 +251,7 @@ SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mec //We got our usable spells so now lets randomly pick one if (!spellCount) - return NULL; + return nullptr; return apSpell[urand(0, spellCount - 1)]; } @@ -327,7 +327,7 @@ void ScriptedAI::DoTeleportAll(float x, float y, float z, float o) Unit* ScriptedAI::DoSelectLowestHpFriendly(float range, uint32 minHPDiff) { - Unit* unit = NULL; + Unit* unit = nullptr; Trinity::MostHPMissingInRange u_check(me, range, minHPDiff); Trinity::UnitLastSearcher<Trinity::MostHPMissingInRange> searcher(me, unit, u_check); me->VisitNearbyObject(range, searcher); @@ -357,7 +357,7 @@ std::list<Creature*> ScriptedAI::DoFindFriendlyMissingBuff(float range, uint32 u Player* ScriptedAI::GetPlayerAtMinimumRange(float minimumRange) { - Player* player = NULL; + Player* player = nullptr; CellCoord pair(Trinity::ComputeCellCoord(me->GetPositionX(), me->GetPositionY())); Cell cell(pair); @@ -507,6 +507,14 @@ void BossAI::_EnterCombat() ScheduleTasks(); } +bool BossAI::CanRespawn() +{ + if (instance && instance->GetBossState(_bossId) == DONE) + return false; + + return true; +} + void BossAI::TeleportCheaters() { float x, y, z; @@ -547,6 +555,39 @@ void BossAI::UpdateAI(uint32 diff) DoMeleeAttackIfReady(); } +void BossAI::_DespawnAtEvade(uint32 delayToRespawn, Creature* who) +{ + if (delayToRespawn < 2) + { + TC_LOG_ERROR("scripts", "_DespawnAtEvade called with delay of %u seconds, defaulting to 2.", delayToRespawn); + delayToRespawn = 2; + } + + if (!who) + who = me; + + if (TempSummon* whoSummon = who->ToTempSummon()) + { + TC_LOG_WARN("scripts", "_DespawnAtEvade called on a temporary summon."); + whoSummon->UnSummon(); + return; + } + + uint32 corpseDelay = who->GetCorpseDelay(); + uint32 respawnDelay = who->GetRespawnDelay(); + + who->SetCorpseDelay(1); + who->SetRespawnDelay(delayToRespawn - 1); + + who->DespawnOrUnsummon(); + + who->SetCorpseDelay(corpseDelay); + who->SetRespawnDelay(respawnDelay); + + if (instance && who == me) + instance->SetBossState(_bossId, FAIL); +} + // WorldBossAI - for non-instanced bosses WorldBossAI::WorldBossAI(Creature* creature) : diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index 5a3107cff5d..6a130d8f20f 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -38,7 +38,7 @@ T* EnsureAI(U* ai) class InstanceScript; -class SummonList +class TC_GAME_API SummonList { public: typedef GuidList StorageType; @@ -114,7 +114,7 @@ public: } } - void DoZoneInCombat(uint32 entry = 0); + void DoZoneInCombat(uint32 entry = 0, float maxRangeToNearestTarget = 250.0f); void RemoveNotExisting(); bool HasEntry(uint32 entry) const; @@ -123,7 +123,7 @@ private: StorageType storage_; }; -class EntryCheckPredicate +class TC_GAME_API EntryCheckPredicate { public: EntryCheckPredicate(uint32 entry) : _entry(entry) { } @@ -133,13 +133,13 @@ class EntryCheckPredicate uint32 _entry; }; -class DummyEntryCheckPredicate +class TC_GAME_API DummyEntryCheckPredicate { public: bool operator()(ObjectGuid) { return true; } }; -struct ScriptedAI : public CreatureAI +struct TC_GAME_API ScriptedAI : public CreatureAI { explicit ScriptedAI(Creature* creature); virtual ~ScriptedAI() { } @@ -334,7 +334,7 @@ struct ScriptedAI : public CreatureAI bool _isHeroic; }; -class BossAI : public ScriptedAI +class TC_GAME_API BossAI : public ScriptedAI { public: BossAI(Creature* creature, uint32 bossId); @@ -361,12 +361,15 @@ class BossAI : public ScriptedAI void JustReachedHome() override { _JustReachedHome(); } bool CanAIAttack(Unit const* target) const override { return CheckBoundary(target); } + bool CanRespawn() override; protected: void _Reset(); void _EnterCombat(); void _JustDied(); void _JustReachedHome() { me->setActive(false); } + void _DespawnAtEvade(uint32 delayToRespawn = 30, Creature* who = nullptr); + void _DespawnAtEvade(Seconds const& time, Creature* who = nullptr) { _DespawnAtEvade(uint32(time.count()), who); } void TeleportCheaters(); @@ -378,7 +381,7 @@ class BossAI : public ScriptedAI uint32 const _bossId; }; -class WorldBossAI : public ScriptedAI +class TC_GAME_API WorldBossAI : public ScriptedAI { public: WorldBossAI(Creature* creature); @@ -409,10 +412,10 @@ class WorldBossAI : public ScriptedAI }; // SD2 grid searchers. -Creature* GetClosestCreatureWithEntry(WorldObject* source, uint32 entry, float maxSearchRange, bool alive = true); -GameObject* GetClosestGameObjectWithEntry(WorldObject* source, uint32 entry, float maxSearchRange); -void GetCreatureListWithEntryInGrid(std::list<Creature*>& list, WorldObject* source, uint32 entry, float maxSearchRange); -void GetGameObjectListWithEntryInGrid(std::list<GameObject*>& list, WorldObject* source, uint32 entry, float maxSearchRange); -void GetPlayerListInGrid(std::list<Player*>& list, WorldObject* source, float maxSearchRange); +TC_GAME_API Creature* GetClosestCreatureWithEntry(WorldObject* source, uint32 entry, float maxSearchRange, bool alive = true); +TC_GAME_API GameObject* GetClosestGameObjectWithEntry(WorldObject* source, uint32 entry, float maxSearchRange); +TC_GAME_API void GetCreatureListWithEntryInGrid(std::list<Creature*>& list, WorldObject* source, uint32 entry, float maxSearchRange); +TC_GAME_API void GetGameObjectListWithEntryInGrid(std::list<GameObject*>& list, WorldObject* source, uint32 entry, float maxSearchRange); +TC_GAME_API void GetPlayerListInGrid(std::list<Player*>& list, WorldObject* source, float maxSearchRange); #endif // SCRIPTEDCREATURE_H_ diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index 68cb8d346d0..1b8b472b805 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -72,7 +72,7 @@ bool npc_escortAI::AssistPlayerInCombat(Unit* who) return false; //experimental (unknown) flag not present - if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS)) + if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_ASSIST)) return false; //not a player @@ -105,7 +105,7 @@ bool npc_escortAI::AssistPlayerInCombat(Unit* who) void npc_escortAI::MoveInLineOfSight(Unit* who) { - if (!me->HasUnitState(UNIT_STATE_STUNNED) && who->isTargetableForAttack() && who->isInAccessiblePlaceFor(me)) + if (me->HasReactState(REACT_AGGRESSIVE) && !me->HasUnitState(UNIT_STATE_STUNNED) && who->isTargetableForAttack() && who->isInAccessiblePlaceFor(me)) { if (HasEscortState(STATE_ESCORT_ESCORTING) && AssistPlayerInCombat(who)) return; diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h index 673f3e671a0..37a1464d812 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h @@ -49,7 +49,7 @@ enum eEscortState STATE_ESCORT_PAUSED = 0x004 //will not proceed with waypoints before state is removed }; -struct npc_escortAI : public ScriptedAI +struct TC_GAME_API npc_escortAI : public ScriptedAI { public: explicit npc_escortAI(Creature* creature); diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp index dc9f6d2681e..bd07e688fb0 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp @@ -69,7 +69,7 @@ bool FollowerAI::AssistPlayerInCombat(Unit* who) return false; //experimental (unknown) flag not present - if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS)) + if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_ASSIST)) return false; //not a player @@ -102,7 +102,7 @@ bool FollowerAI::AssistPlayerInCombat(Unit* who) void FollowerAI::MoveInLineOfSight(Unit* who) { - if (!me->HasUnitState(UNIT_STATE_STUNNED) && who->isTargetableForAttack() && who->isInAccessiblePlaceFor(me)) + if (me->HasReactState(REACT_AGGRESSIVE) && !me->HasUnitState(UNIT_STATE_STUNNED) && who->isTargetableForAttack() && who->isInAccessiblePlaceFor(me)) { if (HasFollowState(STATE_FOLLOW_INPROGRESS) && AssistPlayerInCombat(who)) return; diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h index d1c976b45c8..e17fb7c8507 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h @@ -32,7 +32,7 @@ enum eFollowState STATE_FOLLOW_POSTEVENT = 0x020 //can be set at complete and allow post event to run }; -class FollowerAI : public ScriptedAI +class TC_GAME_API FollowerAI : public ScriptedAI { public: explicit FollowerAI(Creature* creature); diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index eca327e770e..e21f59fe582 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -413,15 +413,10 @@ void SmartAI::EnterEvadeMode(EvadeReason /*why*/) if (!me->IsAlive() || me->IsInEvadeMode()) return; - me->RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE, SPELL_AURA_CLONE_CASTER); + me->RemoveAurasOnEvade(); me->AddUnitState(UNIT_STATE_EVADE); - me->DeleteThreatList(); - me->CombatStop(true); - me->LoadCreaturesAddon(); - me->SetLootRecipient(NULL); - me->ResetPlayerDamageReq(); - me->SetLastDamagedTime(0); + _EnterEvadeMode(); GetScript()->ProcessEventsFor(SMART_EVENT_EVADE);//must be after aura clear so we can cast spells from db @@ -466,11 +461,14 @@ bool SmartAI::CanAIAttack(const Unit* /*who*/) const bool SmartAI::AssistPlayerInCombat(Unit* who) { + if (me->HasReactState(REACT_PASSIVE)) + return false; + if (!who || !who->GetVictim()) return false; //experimental (unknown) flag not present - if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS)) + if (!(me->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_ASSIST)) return false; //not a player @@ -650,8 +648,8 @@ void SmartAI::OnCharmed(bool apply) { GetScript()->ProcessEventsFor(SMART_EVENT_CHARMED, NULL, 0, 0, apply); - if (!apply && !me->IsInEvadeMode() && me->GetCharmerGUID()) - if (Unit* charmer = ObjectAccessor::GetUnit(*me, me->GetCharmerGUID())) + if (!apply && !me->IsInEvadeMode()) + if (Unit* charmer = me->GetCharmer()) AttackStart(charmer); } diff --git a/src/server/game/AI/SmartScripts/SmartAI.h b/src/server/game/AI/SmartScripts/SmartAI.h index 02c057247f6..aa7c9ace0b3 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.h +++ b/src/server/game/AI/SmartScripts/SmartAI.h @@ -42,7 +42,7 @@ enum SmartEscortVars SMART_MAX_AID_DIST = SMART_ESCORT_MAX_PLAYER_DIST / 2 }; -class SmartAI : public CreatureAI +class TC_GAME_API SmartAI : public CreatureAI { public: ~SmartAI(){ } @@ -230,7 +230,7 @@ class SmartAI : public CreatureAI bool mJustReset; }; -class SmartGameObjectAI : public GameObjectAI +class TC_GAME_API SmartGameObjectAI : public GameObjectAI { public: SmartGameObjectAI(GameObject* g) : GameObjectAI(g) { } @@ -257,4 +257,8 @@ class SmartGameObjectAI : public GameObjectAI private: SmartScript mScript; }; + +/// Registers scripts required by the SAI scripting system +void AddSC_SmartScripts(); + #endif diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index c08d1508774..75b9752a193 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -489,7 +489,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u // unless target is outside spell range, out of mana, or LOS. bool _allowMove = false; - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(e.action.cast.spell); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(e.action.cast.spell); int32 mana = me->GetPower(POWER_MANA); if (me->GetDistance(*itr) > spellInfo->GetMaxRange(true) || @@ -929,9 +929,21 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; } - instance->SetData(e.action.setInstanceData.field, e.action.setInstanceData.data); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA: Field: %u, data: %u", - e.action.setInstanceData.field, e.action.setInstanceData.data); + switch (e.action.setInstanceData.type) + { + case 0: + instance->SetData(e.action.setInstanceData.field, e.action.setInstanceData.data); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA: SetData Field: %u, data: %u", + e.action.setInstanceData.field, e.action.setInstanceData.data); + break; + case 1: + instance->SetBossState(e.action.setInstanceData.field, static_cast<EncounterState>(e.action.setInstanceData.data)); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA: SetBossState BossId: %u, State: %u (%s)", + e.action.setInstanceData.field, e.action.setInstanceData.data, InstanceScript::GetBossStateName(e.action.setInstanceData.data).c_str()); + break; + default: // Static analysis + break; + } break; } case SMART_ACTION_SET_INST_DATA64: @@ -1037,10 +1049,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u target->DespawnOrUnsummon(e.action.forceDespawn.delay); } else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - goTarget->SetRespawnTime(e.action.forceDespawn.delay + 1); - } + goTarget->SetRespawnTime(e.action.forceDespawn.delay + 1); } delete targets; @@ -1126,22 +1135,29 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u delete targets; break; } - case SMART_ACTION_MOVE_FORWARD: + case SMART_ACTION_MOVE_OFFSET: { - if (!me) - break; + if (ObjectList* targets = GetTargets(e, unit)) + { + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (!IsCreature(*itr)) + continue; - float x, y, z; - me->GetClosePoint(x, y, z, me->GetObjectSize() / 3, (float)e.action.moveRandom.distance); - me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, x, y, z); - break; - } - case SMART_ACTION_RISE_UP: - { - if (!me) - break; + Position pos = (*itr)->GetPosition(); + + // Use forward/backward/left/right cartesian plane movement + float x, y, z, o; + o = pos.GetOrientation(); + x = pos.GetPositionX() + (std::cos(o - (M_PI / 2))*e.target.x) + (std::cos(o)*e.target.y); + y = pos.GetPositionY() + (std::sin(o - (M_PI / 2))*e.target.x) + (std::sin(o)*e.target.y); + z = pos.GetPositionZ() + e.target.z; + (*itr)->ToCreature()->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, x, y, z); + } + + delete targets; + } - me->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + (float)e.action.moveRandom.distance); break; } case SMART_ACTION_SET_VISIBILITY: @@ -1215,18 +1231,13 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u ObjectList* targets = GetTargets(e, unit); if (targets) { - float x, y, z, o; for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { if (!IsUnit(*itr)) continue; - (*itr)->GetPosition(x, y, z, o); - x += e.target.x; - y += e.target.y; - z += e.target.z; - o += e.target.o; - GetBaseObject()->SummonGameObject(e.action.summonGO.entry, x, y, z, o, 0, 0, 0, 0, e.action.summonGO.despawnTime); + Position pos = (*itr)->GetPositionWithOffset(Position(e.target.x, e.target.y, e.target.z, e.target.o)); + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, pos, G3D::Quat(), e.action.summonGO.despawnTime); } delete targets; @@ -1235,7 +1246,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (e.GetTargetType() != SMART_TARGET_POSITION) break; - GetBaseObject()->SummonGameObject(e.action.summonGO.entry, e.target.x, e.target.y, e.target.z, e.target.o, 0, 0, 0, 0, e.action.summonGO.despawnTime); + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, Position(e.target.x, e.target.y, e.target.z, e.target.o), G3D::Quat(), e.action.summonGO.despawnTime); break; } case SMART_ACTION_KILL_UNIT: @@ -1483,10 +1494,10 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (TransportBase* trans = me->GetDirectTransport()) trans->CalculatePassengerPosition(dest.x, dest.y, dest.z); - me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, dest.x, dest.y, dest.z); + me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, dest.x, dest.y, dest.z, e.action.MoveToPos.disablePathfinding == 0); } else - me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); + me->GetMotionMaster()->MovePoint(e.action.MoveToPos.pointId, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), e.action.MoveToPos.disablePathfinding == 0); break; } case SMART_ACTION_RESPAWN_TARGET: @@ -2330,6 +2341,21 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; } } + case SMART_ACTION_SET_CORPSE_DELAY: + { + ObjectList* targets = GetTargets(e, unit); + if (!targets) + break; + + for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + { + if (IsCreature(*itr)) + (*itr)->ToCreature()->SetCorpseDelay(e.action.corpseDelay.timer); + } + + delete targets; + break; + } default: TC_LOG_ERROR("sql.sql", "SmartScript::ProcessAction: Entry %d SourceType %u, Event %u, Unhandled Action type %u", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); break; @@ -2394,7 +2420,7 @@ void SmartScript::InstallTemplate(SmartScriptHolder const& e) AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, SMART_ACTION_SET_RUN, e.action.installTtemplate.param3, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0); AddEvent(SMART_EVENT_DATA_SET, 0, 0, 0, 0, 0, SMART_ACTION_SET_EVENT_PHASE, 1, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 0); - AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 1000, 1000, 0, 0, SMART_ACTION_MOVE_FORWARD, e.action.installTtemplate.param4, 0, 0, 0, 0, 0, SMART_TARGET_NONE, 0, 0, 0, 1); + AddEvent(SMART_EVENT_UPDATE, SMART_EVENT_FLAG_NOT_REPEATABLE, 1000, 1000, 0, 0, SMART_ACTION_MOVE_OFFSET, 0, 0, 0, 0, 0, 0, SMART_TARGET_SELF, 0, e.action.installTtemplate.param4, 0, 1); //phase 1: give quest credit on movepoint reached AddEvent(SMART_EVENT_MOVEMENTINFORM, 0, POINT_MOTION_TYPE, SMART_RANDOM_POINT, 0, 0, SMART_ACTION_SET_DATA, 0, 0, 0, 0, 0, 0, SMART_TARGET_STORED, 1, 0, 0, 1); //phase 1: despawn after time on movepoint reached @@ -3224,29 +3250,28 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui if (!me) return; - WorldObject* creature = NULL; + Creature* creature = nullptr; if (e.event.distance.guid != 0) { creature = FindCreatureNear(me, e.event.distance.guid); - if (!creature) return; - if (!me->IsInRange(creature, 0, (float)e.event.distance.dist)) + if (!me->IsInRange(creature, 0, static_cast<float>(e.event.distance.dist))) return; } else if (e.event.distance.entry != 0) { std::list<Creature*> list; - me->GetCreatureListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); + me->GetCreatureListWithEntryInGrid(list, e.event.distance.entry, static_cast<float>(e.event.distance.dist)); if (!list.empty()) creature = list.front(); } if (creature) - ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); + ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat, creature); break; } @@ -3255,29 +3280,28 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui if (!me) return; - WorldObject* gameobject = NULL; + GameObject* gameobject = nullptr; if (e.event.distance.guid != 0) { gameobject = FindGameObjectNear(me, e.event.distance.guid); - if (!gameobject) return; - if (!me->IsInRange(gameobject, 0, (float)e.event.distance.dist)) + if (!me->IsInRange(gameobject, 0, static_cast<float>(e.event.distance.dist))) return; } else if (e.event.distance.entry != 0) { std::list<GameObject*> list; - me->GetGameObjectListWithEntryInGrid(list, e.event.distance.entry, (float)e.event.distance.dist); + me->GetGameObjectListWithEntryInGrid(list, e.event.distance.entry, static_cast<float>(e.event.distance.dist)); if (!list.empty()) gameobject = list.front(); } if (gameobject) - ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat); + ProcessTimedAction(e, e.event.distance.repeat, e.event.distance.repeat, nullptr, 0, 0, false, nullptr, gameobject); break; } @@ -3346,6 +3370,16 @@ void SmartScript::UpdateTimer(SmartScriptHolder& e, uint32 const diff) } } + // Delay flee for assist event if stunned or rooted + if (e.GetActionType() == SMART_ACTION_FLEE_FOR_ASSIST) + { + if (me && me->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED)) + { + e.timer = 1; + return; + } + } + e.active = true;//activate events with cooldown switch (e.GetEventType())//process ONLY timed events { diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index e8b89a813b5..a28f2234860 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -28,7 +28,7 @@ #include "SmartScriptMgr.h" //#include "SmartAI.h" -class SmartScript +class TC_GAME_API SmartScript { public: SmartScript(); diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index ef3357fa6ed..f0709eb9216 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -19,6 +19,7 @@ #include "ObjectMgr.h" #include "GridDefines.h" #include "GridNotifiers.h" +#include "InstanceScript.h" #include "SpellMgr.h" #include "Cell.h" #include "GameEventMgr.h" @@ -27,6 +28,12 @@ #include "SmartScriptMgr.h" +SmartWaypointMgr* SmartWaypointMgr::instance() +{ + static SmartWaypointMgr instance; + return &instance; +} + void SmartWaypointMgr::LoadFromDB() { uint32 oldMSTime = getMSTime(); @@ -98,6 +105,12 @@ SmartWaypointMgr::~SmartWaypointMgr() } } +SmartAIMgr* SmartAIMgr::instance() +{ + static SmartAIMgr instance; + return &instance; +} + void SmartAIMgr::LoadSmartAIFromDB() { LoadHelperStores(); @@ -847,7 +860,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (!IsSpellValid(e, e.action.cast.spell)) return false; - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(e.action.cast.spell); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(e.action.cast.spell); for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT) || spellInfo->Effects[j].IsEffect(SPELL_EFFECT_KILL_CREDIT2)) @@ -1144,6 +1157,23 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } break; } + case SMART_ACTION_SET_INST_DATA: + { + if (e.action.setInstanceData.type > 1) + { + TC_LOG_ERROR("sql.sql", "Entry %u SourceType %u Event %u Action %u uses invalid data type %u (value range 0-1), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setInstanceData.type); + return false; + } + else if (e.action.setInstanceData.type == 1) + { + if (e.action.setInstanceData.data > TO_BE_DECIDED) + { + TC_LOG_ERROR("sql.sql", "Entry %u SourceType %u Event %u Action %u uses invalid boss state %u (value range 0-5), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setInstanceData.data); + return false; + } + } + break; + } case SMART_ACTION_START_CLOSEST_WAYPOINT: case SMART_ACTION_FOLLOW: case SMART_ACTION_SET_ORIENTATION: @@ -1161,13 +1191,11 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_ATTACK_START: case SMART_ACTION_THREAT_ALL_PCT: case SMART_ACTION_THREAT_SINGLE_PCT: - case SMART_ACTION_SET_INST_DATA: case SMART_ACTION_SET_INST_DATA64: case SMART_ACTION_AUTO_ATTACK: case SMART_ACTION_ALLOW_COMBAT_MOVEMENT: case SMART_ACTION_CALL_FOR_HELP: case SMART_ACTION_SET_DATA: - case SMART_ACTION_MOVE_FORWARD: case SMART_ACTION_SET_VISIBILITY: case SMART_ACTION_WP_PAUSE: case SMART_ACTION_SET_FLY: @@ -1213,7 +1241,8 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_ADD_GO_FLAG: case SMART_ACTION_REMOVE_GO_FLAG: case SMART_ACTION_SUMMON_CREATURE_GROUP: - case SMART_ACTION_RISE_UP: + case SMART_ACTION_MOVE_OFFSET: + case SMART_ACTION_SET_CORPSE_DELAY: break; default: TC_LOG_ERROR("sql.sql", "SmartAIMgr: Not handled action_type(%u), event_type(%u), Entry %d SourceType %u Event %u, skipped.", e.GetActionType(), e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id); diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index c0ea648462d..8b55c3e138c 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -469,7 +469,7 @@ enum SMART_ACTION SMART_ACTION_RANDOM_PHASE_RANGE = 31, // PhaseMin, PhaseMax SMART_ACTION_RESET_GOBJECT = 32, // SMART_ACTION_CALL_KILLEDMONSTER = 33, // CreatureId, - SMART_ACTION_SET_INST_DATA = 34, // Field, Data + SMART_ACTION_SET_INST_DATA = 34, // Field, Data, Type (0 = SetData, 1 = SetBossState) SMART_ACTION_SET_INST_DATA64 = 35, // Field, SMART_ACTION_UPDATE_TEMPLATE = 36, // Entry SMART_ACTION_DIE = 37, // No Params @@ -481,7 +481,6 @@ enum SMART_ACTION SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL = 43, // Creature_template entry(param1) OR ModelId (param2) (or 0 for both to dismount) SMART_ACTION_SET_INGAME_PHASE_MASK = 44, // mask SMART_ACTION_SET_DATA = 45, // Field, Data (only creature @todo) - SMART_ACTION_MOVE_FORWARD = 46, // distance SMART_ACTION_SET_VISIBILITY = 47, // on/off SMART_ACTION_SET_ACTIVE = 48, // on/off SMART_ACTION_ATTACK_START = 49, // @@ -504,7 +503,7 @@ enum SMART_ACTION SMART_ACTION_SET_ORIENTATION = 66, // SMART_ACTION_CREATE_TIMED_EVENT = 67, // id, InitialMin, InitialMax, RepeatMin(only if it repeats), RepeatMax(only if it repeats), chance SMART_ACTION_PLAYMOVIE = 68, // entry - SMART_ACTION_MOVE_TO_POS = 69, // PointId, xyz + SMART_ACTION_MOVE_TO_POS = 69, // PointId, transport, disablePathfinding SMART_ACTION_RESPAWN_TARGET = 70, // SMART_ACTION_EQUIP = 71, // entry, slotmask slot1, slot2, slot3 , only slots with mask set will be sent to client, bits are 1, 2, 4, leaving mask 0 is defaulted to mask 7 (send all), slots1-3 are only used if no entry is set SMART_ACTION_CLOSE_GOSSIP = 72, // none @@ -549,10 +548,11 @@ enum SMART_ACTION SMART_ACTION_GAME_EVENT_STOP = 111, // GameEventId SMART_ACTION_GAME_EVENT_START = 112, // GameEventId SMART_ACTION_START_CLOSEST_WAYPOINT = 113, // wp1, wp2, wp3, wp4, wp5, wp6, wp7 - SMART_ACTION_RISE_UP = 114, // distance + SMART_ACTION_MOVE_OFFSET = 114, SMART_ACTION_RANDOM_SOUND = 115, // soundId1, soundId2, soundId3, soundId4, soundId5, onlySelf + SMART_ACTION_SET_CORPSE_DELAY = 116, // timer - SMART_ACTION_END = 116 + SMART_ACTION_END = 117 }; struct SmartAction @@ -715,6 +715,7 @@ struct SmartAction { uint32 field; uint32 data; + uint32 type; } setInstanceData; struct @@ -957,6 +958,7 @@ struct SmartAction { uint32 pointId; uint32 transport; + uint32 disablePathfinding; } MoveToPos; struct @@ -1034,6 +1036,11 @@ struct SmartAction uint32 onlySelf; } randomSound; + struct + { + uint32 timer; + } corpseDelay; + //! Note for any new future actions //! All parameters must have type uint32 @@ -1434,18 +1441,14 @@ public: }; typedef std::unordered_map<uint32, ObjectGuidList*> ObjectListMap; -class SmartWaypointMgr +class TC_GAME_API SmartWaypointMgr { private: SmartWaypointMgr() { } ~SmartWaypointMgr(); public: - static SmartWaypointMgr* instance() - { - static SmartWaypointMgr instance; - return &instance; - } + static SmartWaypointMgr* instance(); void LoadFromDB(); @@ -1470,18 +1473,14 @@ typedef std::unordered_map<int32, SmartAIEventList> SmartAIEventMap; typedef std::map<uint32 /*entry*/, std::pair<uint32 /*spellId*/, SpellEffIndex /*effIndex*/> > CacheSpellContainer; typedef std::pair<CacheSpellContainer::const_iterator, CacheSpellContainer::const_iterator> CacheSpellContainerBounds; -class SmartAIMgr +class TC_GAME_API SmartAIMgr { private: SmartAIMgr() { } ~SmartAIMgr() { } public: - static SmartAIMgr* instance() - { - static SmartAIMgr instance; - return &instance; - } + static SmartAIMgr* instance(); void LoadSmartAIFromDB(); diff --git a/src/server/game/Accounts/AccountMgr.cpp b/src/server/game/Accounts/AccountMgr.cpp index 737e9f37195..fa3e8818fe0 100644 --- a/src/server/game/Accounts/AccountMgr.cpp +++ b/src/server/game/Accounts/AccountMgr.cpp @@ -33,17 +33,23 @@ AccountMgr::~AccountMgr() ClearRBAC(); } -AccountOpResult AccountMgr::CreateAccount(std::string username, std::string password, std::string email = "") +AccountMgr* AccountMgr::instance() +{ + static AccountMgr instance; + return &instance; +} + +AccountOpResult AccountMgr::CreateAccount(std::string username, std::string password, std::string email /*= ""*/) { if (utf8length(username) > MAX_ACCOUNT_STR) - return AOR_NAME_TOO_LONG; // username's too long + return AccountOpResult::AOR_NAME_TOO_LONG; // username's too long - normalizeString(username); - normalizeString(password); - normalizeString(email); + Utf8ToUpperOnlyLatin(username); + Utf8ToUpperOnlyLatin(password); + Utf8ToUpperOnlyLatin(email); if (GetId(username)) - return AOR_NAME_ALREADY_EXIST; // username does already exist + return AccountOpResult::AOR_NAME_ALREADY_EXIST; // username does already exist PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT); @@ -57,7 +63,7 @@ AccountOpResult AccountMgr::CreateAccount(std::string username, std::string pass stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS_INIT); LoginDatabase.Execute(stmt); - return AOR_OK; // everything's fine + return AccountOpResult::AOR_OK; // everything's fine } AccountOpResult AccountMgr::DeleteAccount(uint32 accountId) @@ -68,7 +74,7 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accountId) PreparedQueryResult result = LoginDatabase.Query(stmt); if (!result) - return AOR_NAME_NOT_EXIST; + return AccountOpResult::AOR_NAME_NOT_EXIST; // Obtain accounts characters stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID); @@ -128,7 +134,7 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accountId) LoginDatabase.CommitTransaction(trans); - return AOR_OK; + return AccountOpResult::AOR_OK; } AccountOpResult AccountMgr::ChangeUsername(uint32 accountId, std::string newUsername, std::string newPassword) @@ -139,16 +145,16 @@ AccountOpResult AccountMgr::ChangeUsername(uint32 accountId, std::string newUser PreparedQueryResult result = LoginDatabase.Query(stmt); if (!result) - return AOR_NAME_NOT_EXIST; + return AccountOpResult::AOR_NAME_NOT_EXIST; if (utf8length(newUsername) > MAX_ACCOUNT_STR) - return AOR_NAME_TOO_LONG; + return AccountOpResult::AOR_NAME_TOO_LONG; - if (utf8length(newPassword) > MAX_ACCOUNT_STR) - return AOR_PASS_TOO_LONG; + if (utf8length(newPassword) > MAX_PASS_STR) + return AccountOpResult::AOR_PASS_TOO_LONG; - normalizeString(newUsername); - normalizeString(newPassword); + Utf8ToUpperOnlyLatin(newUsername); + Utf8ToUpperOnlyLatin(newPassword); stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_USERNAME); @@ -158,7 +164,7 @@ AccountOpResult AccountMgr::ChangeUsername(uint32 accountId, std::string newUser LoginDatabase.Execute(stmt); - return AOR_OK; + return AccountOpResult::AOR_OK; } AccountOpResult AccountMgr::ChangePassword(uint32 accountId, std::string newPassword) @@ -168,17 +174,17 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accountId, std::string newPass if (!GetName(accountId, username)) { sScriptMgr->OnFailedPasswordChange(accountId); - return AOR_NAME_NOT_EXIST; // account doesn't exist + return AccountOpResult::AOR_NAME_NOT_EXIST; // account doesn't exist } - if (utf8length(newPassword) > MAX_ACCOUNT_STR) + if (utf8length(newPassword) > MAX_PASS_STR) { sScriptMgr->OnFailedPasswordChange(accountId); - return AOR_PASS_TOO_LONG; + return AccountOpResult::AOR_PASS_TOO_LONG; } - normalizeString(username); - normalizeString(newPassword); + Utf8ToUpperOnlyLatin(username); + Utf8ToUpperOnlyLatin(newPassword); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_PASSWORD); @@ -196,7 +202,7 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accountId, std::string newPass LoginDatabase.Execute(stmt); sScriptMgr->OnPasswordChange(accountId); - return AOR_OK; + return AccountOpResult::AOR_OK; } AccountOpResult AccountMgr::ChangeEmail(uint32 accountId, std::string newEmail) @@ -206,17 +212,17 @@ AccountOpResult AccountMgr::ChangeEmail(uint32 accountId, std::string newEmail) if (!GetName(accountId, username)) { sScriptMgr->OnFailedEmailChange(accountId); - return AOR_NAME_NOT_EXIST; // account doesn't exist + return AccountOpResult::AOR_NAME_NOT_EXIST; // account doesn't exist } if (utf8length(newEmail) > MAX_EMAIL_STR) { sScriptMgr->OnFailedEmailChange(accountId); - return AOR_EMAIL_TOO_LONG; + return AccountOpResult::AOR_EMAIL_TOO_LONG; } - normalizeString(username); - normalizeString(newEmail); + Utf8ToUpperOnlyLatin(username); + Utf8ToUpperOnlyLatin(newEmail); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_EMAIL); @@ -226,7 +232,7 @@ AccountOpResult AccountMgr::ChangeEmail(uint32 accountId, std::string newEmail) LoginDatabase.Execute(stmt); sScriptMgr->OnEmailChange(accountId); - return AOR_OK; + return AccountOpResult::AOR_OK; } AccountOpResult AccountMgr::ChangeRegEmail(uint32 accountId, std::string newEmail) @@ -236,17 +242,17 @@ AccountOpResult AccountMgr::ChangeRegEmail(uint32 accountId, std::string newEmai if (!GetName(accountId, username)) { sScriptMgr->OnFailedEmailChange(accountId); - return AOR_NAME_NOT_EXIST; // account doesn't exist + return AccountOpResult::AOR_NAME_NOT_EXIST; // account doesn't exist } if (utf8length(newEmail) > MAX_EMAIL_STR) { sScriptMgr->OnFailedEmailChange(accountId); - return AOR_EMAIL_TOO_LONG; + return AccountOpResult::AOR_EMAIL_TOO_LONG; } - normalizeString(username); - normalizeString(newEmail); + Utf8ToUpperOnlyLatin(username); + Utf8ToUpperOnlyLatin(newEmail); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_REG_EMAIL); @@ -256,7 +262,7 @@ AccountOpResult AccountMgr::ChangeRegEmail(uint32 accountId, std::string newEmai LoginDatabase.Execute(stmt); sScriptMgr->OnEmailChange(accountId); - return AOR_OK; + return AccountOpResult::AOR_OK; } uint32 AccountMgr::GetId(std::string const& username) @@ -324,8 +330,8 @@ bool AccountMgr::CheckPassword(uint32 accountId, std::string password) if (!GetName(accountId, username)) return false; - normalizeString(username); - normalizeString(password); + Utf8ToUpperOnlyLatin(username); + Utf8ToUpperOnlyLatin(password); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD); stmt->setUInt32(0, accountId); @@ -343,8 +349,8 @@ bool AccountMgr::CheckEmail(uint32 accountId, std::string newEmail) if (!GetEmail(accountId, oldEmail)) return false; - normalizeString(oldEmail); - normalizeString(newEmail); + Utf8ToUpperOnlyLatin(oldEmail); + Utf8ToUpperOnlyLatin(newEmail); if (strcmp(oldEmail.c_str(), newEmail.c_str()) == 0) return true; @@ -362,19 +368,6 @@ uint32 AccountMgr::GetCharactersCount(uint32 accountId) return (result) ? (*result)[0].GetUInt64() : 0; } -bool AccountMgr::normalizeString(std::string& utf8String) -{ - wchar_t buffer[MAX_ACCOUNT_STR+1]; - - size_t maxLength = MAX_ACCOUNT_STR; - if (!Utf8toWStr(utf8String, buffer, maxLength)) - return false; - - std::transform(&buffer[0], buffer+maxLength, &buffer[0], wcharToUpperOnlyLatin); - - return WStrToUtf8(buffer, maxLength, utf8String); -} - std::string AccountMgr::CalculateShaPassHash(std::string const& name, std::string const& password) { SHA1Hash sha; @@ -462,7 +455,7 @@ void AccountMgr::LoadRBAC() while (result->NextRow()); TC_LOG_DEBUG("rbac", "AccountMgr::LoadRBAC: Loading default permissions"); - result = LoginDatabase.PQuery("SELECT secId, permissionId FROM rbac_default_permissions WHERE (realmId = %u OR realmId = -1) ORDER BY secId ASC", realmID); + result = LoginDatabase.PQuery("SELECT secId, permissionId FROM rbac_default_permissions WHERE (realmId = %u OR realmId = -1) ORDER BY secId ASC", realm.Id.Realm); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 default permission definitions. DB table `rbac_default_permissions` is empty."); @@ -494,19 +487,20 @@ void AccountMgr::UpdateAccountAccess(rbac::RBACData* rbac, uint32 accountId, uin if (rbac && securityLevel == rbac->GetSecurityLevel()) rbac->SetSecurityLevel(securityLevel); + SQLTransaction trans = LoginDatabase.BeginTransaction(); // Delete old security level from DB if (realmId == -1) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_ACCOUNT_ACCESS); stmt->setUInt32(0, accountId); - LoginDatabase.Execute(stmt); + trans->Append(stmt); } else { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_ACCOUNT_ACCESS_BY_REALM); stmt->setUInt32(0, accountId); stmt->setUInt32(1, realmId); - LoginDatabase.Execute(stmt); + trans->Append(stmt); } // Add new security level @@ -516,8 +510,10 @@ void AccountMgr::UpdateAccountAccess(rbac::RBACData* rbac, uint32 accountId, uin stmt->setUInt32(0, accountId); stmt->setUInt8(1, securityLevel); stmt->setInt32(2, realmId); - LoginDatabase.Execute(stmt); + trans->Append(stmt); } + + LoginDatabase.CommitTransaction(trans); } rbac::RBACPermission const* AccountMgr::GetRBACPermission(uint32 permissionId) const diff --git a/src/server/game/Accounts/AccountMgr.h b/src/server/game/Accounts/AccountMgr.h index 40ccba1f8e5..f3bb1abe64e 100644 --- a/src/server/game/Accounts/AccountMgr.h +++ b/src/server/game/Accounts/AccountMgr.h @@ -21,7 +21,7 @@ #include "RBAC.h" -enum AccountOpResult +enum class AccountOpResult : uint8 { AOR_OK, AOR_NAME_TOO_LONG, @@ -39,6 +39,7 @@ enum PasswordChangeSecurity PW_RBAC }; +#define MAX_PASS_STR 16 #define MAX_ACCOUNT_STR 16 #define MAX_EMAIL_STR 64 @@ -48,20 +49,16 @@ typedef std::map<uint32, rbac::RBACPermission*> RBACPermissionsContainer; typedef std::map<uint8, rbac::RBACPermissionContainer> RBACDefaultPermissionsContainer; } -class AccountMgr +class TC_GAME_API AccountMgr { private: AccountMgr(); ~AccountMgr(); public: - static AccountMgr* instance() - { - static AccountMgr instance; - return &instance; - } + static AccountMgr* instance(); - AccountOpResult CreateAccount(std::string username, std::string password, std::string email); + AccountOpResult CreateAccount(std::string username, std::string password, std::string email = ""); static AccountOpResult DeleteAccount(uint32 accountId); static AccountOpResult ChangeUsername(uint32 accountId, std::string newUsername, std::string newPassword); static AccountOpResult ChangePassword(uint32 accountId, std::string newPassword); @@ -78,7 +75,6 @@ class AccountMgr static uint32 GetCharactersCount(uint32 accountId); static std::string CalculateShaPassHash(std::string const& name, std::string const& password); - static bool normalizeString(std::string& utf8String); static bool IsPlayerAccount(uint32 gmlevel); static bool IsAdminAccount(uint32 gmlevel); static bool IsConsoleAccount(uint32 gmlevel); diff --git a/src/server/game/Accounts/RBAC.cpp b/src/server/game/Accounts/RBAC.cpp index a8720b66df4..34d7687452c 100644 --- a/src/server/game/Accounts/RBAC.cpp +++ b/src/server/game/Accounts/RBAC.cpp @@ -236,10 +236,10 @@ void RBACData::AddPermissions(RBACPermissionContainer const& permsFrom, RBACPerm permsTo.insert(*itr); } -void RBACData::RemovePermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo) +void RBACData::RemovePermissions(RBACPermissionContainer& permsFrom, RBACPermissionContainer const& permsToRemove) { - for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr) - permsTo.erase(*itr); + for (RBACPermissionContainer::const_iterator itr = permsToRemove.begin(); itr != permsToRemove.end(); ++itr) + permsFrom.erase(*itr); } void RBACData::ExpandPermissions(RBACPermissionContainer& permissions) diff --git a/src/server/game/Accounts/RBAC.h b/src/server/game/Accounts/RBAC.h index 4ebd3ae7042..741983431dd 100644 --- a/src/server/game/Accounts/RBAC.h +++ b/src/server/game/Accounts/RBAC.h @@ -59,9 +59,9 @@ enum RBACPermissions // 7 - reuse // 8 - reuse // 9 - reuse - // 10 - reuse + // 10 - 7.x only RBAC_PERM_LOG_GM_TRADE = 11, - // 12 - reuse + // 12 - 7.x only RBAC_PERM_SKIP_CHECK_INSTANCE_REQUIRED_BOSSES = 13, RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_TEAMMASK = 14, RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_CLASSMASK = 15, @@ -540,7 +540,7 @@ enum RBACPermissions RBAC_PERM_COMMAND_RELOAD_DISENCHANT_LOOT_TEMPLATE = 642, RBAC_PERM_COMMAND_RELOAD_EVENT_SCRIPTS = 643, RBAC_PERM_COMMAND_RELOAD_FISHING_LOOT_TEMPLATE = 644, - RBAC_PERM_COMMAND_RELOAD_GAME_GRAVEYARD_ZONE = 645, + RBAC_PERM_COMMAND_RELOAD_GRAVEYARD_ZONE = 645, RBAC_PERM_COMMAND_RELOAD_GAME_TELE = 646, RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUESTENDER = 647, RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUEST_LOOT_TEMPLATE = 648, @@ -670,8 +670,8 @@ enum RBACPermissions RBAC_PERM_COMMAND_WP_UNLOAD = 772, RBAC_PERM_COMMAND_WP_RELOAD = 773, RBAC_PERM_COMMAND_WP_SHOW = 774, - RBAC_PERM_COMMAND_MODIFY_CURRENCY = 775, // only 4.3.4 - RBAC_PERM_COMMAND_DEBUG_PHASE = 776, // only 4.3.4 + RBAC_PERM_COMMAND_MODIFY_CURRENCY = 775, // only 6.x + RBAC_PERM_COMMAND_DEBUG_PHASE = 776, // only 6.x RBAC_PERM_COMMAND_MAILBOX = 777, RBAC_PERM_COMMAND_AHBOT = 778, RBAC_PERM_COMMAND_AHBOT_ITEMS = 779, @@ -697,6 +697,11 @@ enum RBACPermissions // 799 - 834 6.x only RBAC_PERM_COMMAND_DEBUG_LOADCELLS = 835, RBAC_PERM_COMMAND_DEBUG_BOUNDARY = 836, + RBAC_PERM_COMMAND_NPC_EVADE = 837, + RBAC_PERM_COMMAND_PET_LEVEL = 838, + RBAC_PERM_COMMAND_SERVER_SHUTDOWN_FORCE = 839, + RBAC_PERM_COMMAND_SERVER_RESTART_FORCE = 840, + RBAC_PERM_COMMAND_NEARGRAVEYARD = 841, // custom permissions 1000+ RBAC_PERM_MAX @@ -714,7 +719,7 @@ enum RBACCommandResult typedef std::set<uint32> RBACPermissionContainer; -class RBACPermission +class TC_GAME_API RBACPermission { public: RBACPermission(uint32 id = 0, std::string const& name = ""): @@ -749,7 +754,7 @@ class RBACPermission * - Granted permissions: through linked permissions and directly assigned * - Denied permissions: through linked permissions and directly assigned */ -class RBACData +class TC_GAME_API RBACData { public: RBACData(uint32 id, std::string const& name, int32 realmId, uint8 secLevel = 255): @@ -938,8 +943,8 @@ class RBACData /// Adds a list of permissions to another list void AddPermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo); - /// Removes a list of permissions to another list - void RemovePermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo); + /// Removes a list of permissions from another list + void RemovePermissions(RBACPermissionContainer& permsFrom, RBACPermissionContainer const& permsToRemove); /** * @name ExpandPermissions diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index ac8e0298a44..11c2635da33 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -46,7 +46,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) { if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.", criteria->ID, dataType); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: %u) contains a wrong data type (%u), ignored.", criteria->ID, dataType); return false; } @@ -81,7 +81,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) default: if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->requiredType); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` contains data for a non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->requiredType); return false; } break; @@ -96,7 +96,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE: if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) contains a non-existing creature id in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, creature.id); return false; } @@ -104,13 +104,13 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE: if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) contains a non-existing class in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) contains a non-existing race in value2 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } @@ -118,7 +118,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH: if (health.percent < 1 || health.percent > 100) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) contains a wrong percent value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, health.percent); return false; } @@ -126,7 +126,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD: if (player_dead.own_team_flag > 1) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD (%u) has wrong boolean value1 (%u).", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD (%u) contains a wrong boolean value1 (%u).", criteria->ID, criteria->requiredType, dataType, player_dead.own_team_flag); return false; } @@ -137,19 +137,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id); if (!spellEntry) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) contains a wrong spell id in value1 (%u), ignored.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); return false; } if (aura.effect_idx >= 3) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) contains a wrong spell effect index in value2 (%u), ignored.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); return false; } if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) contains a non-aura spell effect (ID: %u Effect: %u), ignored.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); return false; } @@ -158,7 +158,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA: if (!sAreaTableStore.LookupEntry(area.id)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA (%u) has wrong area id in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA (%u) contains a wrong area id in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, area.id); return false; } @@ -166,7 +166,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: if (value.compType >= COMP_TYPE_MAX) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE (%u) has wrong ComparisionType in value2 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE (%u) contains a wrong ComparisionType in value2 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, value.compType); return false; } @@ -174,7 +174,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL: if (level.minlevel > STRONG_MAX_LEVEL) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) contains a wrong minlevel in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, level.minlevel); return false; } @@ -182,7 +182,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER: if (gender.gender > GENDER_NONE) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) contains a wrong gender value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, gender.gender); return false; } @@ -190,7 +190,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT: if (!ScriptId) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have a ScriptName set, ignored.", criteria->ID, criteria->requiredType, dataType); return false; } @@ -198,7 +198,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY: if (difficulty.difficulty >= MAX_DIFFICULTY) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY (%u) has wrong difficulty in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY (%u) contains a wrong difficulty value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, difficulty.difficulty); return false; } @@ -206,7 +206,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT: if (map_players.maxcount <= 0) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) contains a wrong max players count in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, map_players.maxcount); return false; } @@ -214,7 +214,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM: if (team.team != ALLIANCE && team.team != HORDE) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) contains an unknown team value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, team.team); return false; } @@ -222,7 +222,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK: if (drunk.state >= MAX_DRUNKEN) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) contains an unknown drunken state value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, drunk.state); return false; } @@ -230,7 +230,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY: if (!sHolidaysStore.LookupEntry(holiday.id)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) contains an unknown holiday entry in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, holiday.id); return false; } @@ -240,7 +240,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: if (equipped_item.item_quality >= MAX_ITEM_QUALITY) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM (%u) contains an unknown quality state value in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, equipped_item.item_quality); return false; } @@ -248,7 +248,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID: if (!sMapStore.LookupEntry(map_id.mapId)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID (%u) has unknown map id in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID (%u) contains an unknown map id in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, map_id.mapId); return false; } @@ -256,19 +256,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE: if (!classRace.class_id && !classRace.race_id) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) should not have 0 in either value field. Ignored.", criteria->ID, criteria->requiredType, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) contains a non-existing class entry in value1 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) contains a non-existing race entry in value2 (%u), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } @@ -276,13 +276,13 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE: if (!sCharTitlesStore.LookupEntry(known_title.title_id)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE (%u) have unknown title_id in value1 (%u), ignore.", + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE (%u) contains an unknown title_id in value1 (%u), ignore.", criteria->ID, criteria->requiredType, dataType, known_title.title_id); return false; } return true; default: - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->requiredType, dataType); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) contains data of a non-supported data type (%u), ignored.", criteria->ID, criteria->requiredType, dataType); return false; } } @@ -377,14 +377,14 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un Map* map = source->GetMap(); if (!map->IsDungeon()) { - TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u", + TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u in a non-dungeon/non-raid map %u", dataType, criteria_id, map->GetId()); return false; } InstanceScript* instance = map->ToInstanceMap()->GetInstanceScript(); if (!instance) { - TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script", + TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT (%u) for achievement criteria %u in map %u, but the map does not have an instance script.", dataType, criteria_id, map->GetId()); return false; } @@ -601,8 +601,8 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, PreparedQ AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id); if (!criteria) { - // we will remove not existed criteria for all characters - TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id); + // Removing non-existing criteria data for all characters + TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data has been removed from the table `character_achievement_progress`.", id); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA); @@ -646,13 +646,20 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH)) { + uint32 team = GetPlayer()->GetTeam(); + // broadcast realm first reached WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, GetPlayer()->GetName().size() + 1 + 8 + 4 + 4); data << GetPlayer()->GetName(); data << uint64(GetPlayer()->GetGUID()); data << uint32(achievement->ID); - data << uint32(0); // 1=link supplied string as player name, 0=display plain string - sWorld->SendGlobalMessage(&data); + + std::size_t linkTypePos = data.wpos(); + data << uint32(1); // display name as clickable link in chat + sWorld->SendGlobalMessage(&data, nullptr, team); + + data.put<uint32>(linkTypePos, 0); // display name as plain string in chat + sWorld->SendGlobalMessage(&data, nullptr, team == ALLIANCE ? HORDE : ALLIANCE); } // if player is in world he can tell his friends about new achievement else if (GetPlayer()->IsInWorld()) @@ -1066,7 +1073,7 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui break; } - // std case: not exist in DBC, not triggered in code as result + // std case: does not exist in DBC, not triggered in code as result case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALTH: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_SPELLPOWER: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_ARMOR: @@ -1404,7 +1411,7 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry, if (entry->timeLimit) { - // has to exist else we wouldn't be here + // has to exist, otherwise we wouldn't be here timedCompleted = IsCompletedCriteria(entry, sAchievementMgr->GetAchievement(entry->referredAchievement)); // Client expects this in packet timeElapsed = entry->timeLimit - (timedIter->second/IN_MILLISECONDS); @@ -1533,7 +1540,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) //! Since no common attributes were found, (not even in titleRewardFlags field) //! we explicitly check by ID. Maybe in the future we could move the achievement_reward //! condition fields to the condition system. - if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetPlayer()->GetByteValue(PLAYER_BYTES_3, 0) : (GetPlayer()->GetTeam() == ALLIANCE ? 0 : 1)]) + if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetPlayer()->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER) : (GetPlayer()->GetTeam() == ALLIANCE ? 0 : 1)]) if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId)) GetPlayer()->SetTitle(titleEntry); @@ -1655,14 +1662,14 @@ bool AchievementMgr::CanUpdateCriteria(AchievementCriteriaEntry const* criteria, if (!RequirementsSatisfied(criteria, achievement, miscValue1, miscValue2, unit)) { - TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Requirements not satisfied", + TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Requirements have not been satisfied", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->requiredType)); return false; } if (!ConditionsSatisfied(criteria)) { - TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Conditions not satisfied", + TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Conditions have not been satisfied", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->requiredType)); return false; } @@ -2246,6 +2253,12 @@ char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes return "MISSING_TYPE"; } +AchievementGlobalMgr* AchievementGlobalMgr::instance() +{ + static AchievementGlobalMgr instance; + return &instance; +} + //========================================================== void AchievementGlobalMgr::LoadAchievementCriteriaList() { @@ -2273,7 +2286,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaList() ++loaded; } - TC_LOG_INFO("server.loading", ">> Loaded %u achievement criteria in %u ms", loaded, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u achievement criteria in %u ms.", loaded, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadAchievementReferenceList() @@ -2302,7 +2315,7 @@ void AchievementGlobalMgr::LoadAchievementReferenceList() if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539)) const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar) - TC_LOG_INFO("server.loading", ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u achievement references in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadAchievementCriteriaData() @@ -2330,7 +2343,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() if (!criteria) { - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.", criteria_id); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` contains data for non-existing criteria (Entry: %u). Ignored.", criteria_id); continue; } @@ -2340,7 +2353,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() if (scriptName.length()) // not empty { if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` contains a ScriptName for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType); else scriptId = sObjectMgr->GetScriptId(scriptName); } @@ -2396,7 +2409,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() if (!achievement) continue; - // exist many achievements with this criteria, use at this moment hardcoded check to skil simple case + // There are many achievements with these criteria, use hardcoded check at this moment to pick a simple case if (achievement->ID == 1282) break; @@ -2433,7 +2446,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() } if (!GetCriteriaDataSet(criteria) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, entryId, NULL)) - TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` does not have expected data for criteria (Entry: %u Type: %u) for achievement %u.", criteria->ID, criteria->requiredType, criteria->referredAchievement); + TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` does not contain expected data for criteria (Entry: %u Type: %u) for achievement %u.", criteria->ID, criteria->requiredType, criteria->referredAchievement); } TC_LOG_INFO("server.loading", ">> Loaded %u additional achievement criteria data in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -2459,8 +2472,8 @@ void AchievementGlobalMgr::LoadCompletedAchievements() const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId); if (!achievement) { - // Remove non existent achievements from all characters - TC_LOG_ERROR("achievement", "Non-existing achievement %u data removed from table `character_achievement`.", achievementId); + // Remove non-existing achievements from all characters + TC_LOG_ERROR("achievement", "Non-existing achievement %u data has been removed from the table `character_achievement`.", achievementId); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT); stmt->setUInt16(0, uint16(achievementId)); @@ -2473,7 +2486,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %lu realm first completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %lu realm first completed achievements in %u ms.", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadRewards() @@ -2500,7 +2513,7 @@ void AchievementGlobalMgr::LoadRewards() AchievementEntry const* achievement = GetAchievement(entry); if (!achievement) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` contains a wrong achievement entry (Entry: %u), ignored.", entry); continue; } @@ -2516,19 +2529,19 @@ void AchievementGlobalMgr::LoadRewards() // must be title or mail at least if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not contain title or item reward data. Ignored.", entry); continue; } if (achievement->requiredFaction == ACHIEVEMENT_FACTION_ANY && (!reward.titleId[0] ^ !reward.titleId[1])) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) contains the title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]); if (reward.titleId[0]) { CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]); if (!titleEntry) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) contains an invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]); reward.titleId[0] = 0; } } @@ -2538,7 +2551,7 @@ void AchievementGlobalMgr::LoadRewards() CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]); if (!titleEntry) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) contains an invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]); reward.titleId[1] = 0; } } @@ -2548,41 +2561,41 @@ void AchievementGlobalMgr::LoadRewards() { if (!sObjectMgr->GetCreatureTemplate(reward.sender)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) contains an invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender); reward.sender = 0; } } else { if (reward.itemId) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data, but contains an item reward. Item will not be rewarded.", entry); if (!reward.subject.empty()) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data, but contains a mail subject.", entry); if (!reward.text.empty()) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data, but contains mail text.", entry); if (reward.mailTemplate) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mailTemplate.", entry); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data, but has a mailTemplate.", entry); } if (reward.mailTemplate) { if (!sMailTemplateStore.LookupEntry(reward.mailTemplate)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid mailTemplate (%u).", entry, reward.mailTemplate); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) is using an invalid mailTemplate (%u).", entry, reward.mailTemplate); reward.mailTemplate = 0; } else if (!reward.subject.empty() || !reward.text.empty()) - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has mailTemplate (%u) and mail subject/text.", entry, reward.mailTemplate); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) is using mailTemplate (%u) and mail subject/text.", entry, reward.mailTemplate); } if (reward.itemId) { if (!sObjectMgr->GetItemTemplate(reward.itemId)) { - TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.", entry, reward.itemId); + TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) contains an invalid item id %u, reward mail will not contain the rewarded item.", entry, reward.itemId); reward.itemId = 0; } } @@ -2592,7 +2605,7 @@ void AchievementGlobalMgr::LoadRewards() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u achievement rewards in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadRewardLocales() @@ -2607,7 +2620,7 @@ void AchievementGlobalMgr::LoadRewardLocales() if (!result) { - TC_LOG_INFO("server.loading", ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty"); + TC_LOG_INFO("server.loading", ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty."); return; } @@ -2619,7 +2632,7 @@ void AchievementGlobalMgr::LoadRewardLocales() if (m_achievementRewards.find(entry) == m_achievementRewards.end()) { - TC_LOG_ERROR("sql.sql", "Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.", entry); + TC_LOG_ERROR("sql.sql", "Table `locales_achievement_reward` (Entry: %u) contains locale strings for a non-existing achievement reward.", entry); continue; } @@ -2634,7 +2647,7 @@ void AchievementGlobalMgr::LoadRewardLocales() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u achievement reward locale strings in %u ms", uint32(m_achievementRewardLocales.size()), GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u achievement reward locale strings in %u ms.", uint32(m_achievementRewardLocales.size()), GetMSTimeDiffToNow(oldMSTime)); } AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index cc3fd55bc3a..c4ac5f0e808 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -212,7 +212,7 @@ struct AchievementCriteriaData bool Meets(uint32 criteria_id, Player const* source, Unit const* target, uint32 miscValue1 = 0) const; }; -struct AchievementCriteriaDataSet +struct TC_GAME_API AchievementCriteriaDataSet { AchievementCriteriaDataSet() : criteria_id(0) { } typedef std::vector<AchievementCriteriaData> Storage; @@ -262,7 +262,7 @@ enum ProgressType PROGRESS_HIGHEST }; -class AchievementMgr +class TC_GAME_API AchievementMgr { public: AchievementMgr(Player* player); @@ -306,7 +306,7 @@ class AchievementMgr TimedAchievementMap m_timedAchievements; // Criteria id/time left in MS }; -class AchievementGlobalMgr +class TC_GAME_API AchievementGlobalMgr { AchievementGlobalMgr() { } ~AchievementGlobalMgr() { } @@ -315,11 +315,7 @@ class AchievementGlobalMgr static char const* GetCriteriaTypeString(AchievementCriteriaTypes type); static char const* GetCriteriaTypeString(uint32 type); - static AchievementGlobalMgr* instance() - { - static AchievementGlobalMgr instance; - return &instance; - } + static AchievementGlobalMgr* instance(); AchievementCriteriaEntryList const& GetAchievementCriteriaByType(AchievementCriteriaTypes type) const { diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index 035d9af4369..d9f5388e3ce 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -44,6 +44,12 @@ AuctionHouseMgr::~AuctionHouseMgr() delete itr->second; } +AuctionHouseMgr* AuctionHouseMgr::instance() +{ + static AuctionHouseMgr instance; + return &instance; +} + AuctionHouseObject* AuctionHouseMgr::GetAuctionsMap(uint32 factionTemplateId) { if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION)) @@ -130,7 +136,7 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry* auction, SQLTransaction& else { bidderAccId = sObjectMgr->GetPlayerAccountIdByGUID(bidderGuid); - logGmTrade = AccountMgr::HasPermission(bidderAccId, rbac::RBAC_PERM_LOG_GM_TRADE, realmID); + logGmTrade = AccountMgr::HasPermission(bidderAccId, rbac::RBAC_PERM_LOG_GM_TRADE, realm.Id.Realm); if (logGmTrade && !sObjectMgr->GetPlayerNameByGUID(bidderGuid, bidderName)) bidderName = sObjectMgr->GetTrinityStringForDBCLocale(LANG_UNKNOWN); diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index fe4b9ed07de..42322929a30 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -70,7 +70,7 @@ enum AuctionHouses AUCTIONHOUSE_NEUTRAL = 7 }; -struct AuctionEntry +struct TC_GAME_API AuctionEntry { uint32 Id; uint8 houseId; @@ -101,7 +101,7 @@ struct AuctionEntry }; //this class is used as auctionhouse instance -class AuctionHouseObject +class TC_GAME_API AuctionHouseObject { public: ~AuctionHouseObject() @@ -146,18 +146,14 @@ class AuctionHouseObject }; -class AuctionHouseMgr +class TC_GAME_API AuctionHouseMgr { private: AuctionHouseMgr(); ~AuctionHouseMgr(); public: - static AuctionHouseMgr* instance() - { - static AuctionHouseMgr instance; - return &instance; - } + static AuctionHouseMgr* instance(); typedef std::unordered_map<ObjectGuid::LowType, Item*> ItemMap; typedef std::vector<AuctionEntry*> PlayerAuctions; diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp index e1ba9a64191..74f0aaf428a 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp @@ -24,6 +24,12 @@ #include "AuctionHouseBotBuyer.h" #include "AuctionHouseBotSeller.h" +AuctionBotConfig* AuctionBotConfig::instance() +{ + static AuctionBotConfig instance; + return &instance; +} + bool AuctionBotConfig::Initialize() { GetConfigFromFile(); @@ -426,6 +432,12 @@ void AuctionHouseBot::Rebuild(bool all) } } +AuctionHouseBot* AuctionHouseBot::instance() +{ + static AuctionHouseBot instance; + return &instance; +} + void AuctionHouseBot::Update() { // nothing do... diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.h b/src/server/game/AuctionHouseBot/AuctionHouseBot.h index 87f76a17dcc..1a438e01cdb 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.h @@ -196,7 +196,7 @@ enum AuctionBotConfigFloatValues }; // All basic config data used by other AHBot classes for self-configure. -class AuctionBotConfig +class TC_GAME_API AuctionBotConfig { private: AuctionBotConfig(): _itemsPerCycleBoost(1000), _itemsPerCycleNormal(20) {} @@ -205,11 +205,7 @@ private: AuctionBotConfig& operator=(const AuctionBotConfig&); public: - static AuctionBotConfig* instance() - { - static AuctionBotConfig instance; - return &instance; - } + static AuctionBotConfig* instance(); bool Initialize(); const std::string& GetAHBotIncludes() const { return _AHBotIncludes; } @@ -274,7 +270,7 @@ typedef AuctionHouseBotStatusInfoPerType AuctionHouseBotStatusInfo[MAX_AUCTION_H // This class handle both Selling and Buying method // (holder of AuctionBotBuyer and AuctionBotSeller objects) -class AuctionHouseBot +class TC_GAME_API AuctionHouseBot { private: AuctionHouseBot(); @@ -283,11 +279,7 @@ private: AuctionHouseBot& operator=(const AuctionHouseBot&); public: - static AuctionHouseBot* instance() - { - static AuctionHouseBot instance; - return &instance; - } + static AuctionHouseBot* instance(); void Update(); void Initialize(); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp index 7f05cd2efd7..6b1dcb85bec 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp @@ -17,7 +17,7 @@ #include "Log.h" #include "Item.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" #include "AuctionHouseBotBuyer.h" AuctionBotBuyer::AuctionBotBuyer() : _checkInterval(20 * MINUTE) diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h index e1b6b425c48..979f73c0099 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h @@ -67,7 +67,7 @@ private: // This class handle all Buyer method // (holder of AuctionBotConfig for each auction house type) -class AuctionBotBuyer : public AuctionBotAgent +class TC_GAME_API AuctionBotBuyer : public AuctionBotAgent { public: AuctionBotBuyer(); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp index 5acb56b5173..17b104eb388 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp @@ -582,13 +582,13 @@ void AuctionBotSeller::LoadSellerValues(SellerConfiguration& config) break; } - config.SetPriceRatioPerQuality(AUCTION_QUALITY_GRAY, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_GRAY_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_WHITE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_WHITE_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_GREEN, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_GREEN_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_BLUE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_BLUE_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_PURPLE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_PURPLE_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_ORANGE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_ORANGE_PRICE_RATIO) / 100); - config.SetPriceRatioPerQuality(AUCTION_QUALITY_YELLOW, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_YELLOW_PRICE_RATIO) / 100); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_GRAY, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_GRAY_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_WHITE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_WHITE_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_GREEN, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_GREEN_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_BLUE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_BLUE_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_PURPLE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_PURPLE_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_ORANGE, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_ORANGE_PRICE_RATIO)); + config.SetPriceRatioPerQuality(AUCTION_QUALITY_YELLOW, PriceRatio * sAuctionBotConfig->GetConfig(CONFIG_AHBOT_ITEM_YELLOW_PRICE_RATIO)); config.SetPriceRatioPerClass(ITEM_CLASS_CONSUMABLE, sAuctionBotConfig->GetConfig(CONFIG_AHBOT_CLASS_CONSUMABLE_PRICE_RATIO)); config.SetPriceRatioPerClass(ITEM_CLASS_CONTAINER, sAuctionBotConfig->GetConfig(CONFIG_AHBOT_CLASS_CONTAINER_PRICE_RATIO)); @@ -701,10 +701,10 @@ void AuctionBotSeller::SetPricesOfItem(ItemTemplate const* itemProto, SellerConf { uint32 classRatio = config.GetPriceRatioPerClass(ItemClass(itemProto->Class)); uint32 qualityRatio = config.GetPriceRatioPerQuality(AuctionQuality(itemProto->Quality)); - uint32 priceRatio = (classRatio * qualityRatio) / 100; + float priceRatio = (classRatio * qualityRatio) / 10000.0f; - uint32 buyPrice = itemProto->BuyPrice; - uint32 sellPrice = itemProto->SellPrice; + float buyPrice = itemProto->BuyPrice; + float sellPrice = itemProto->SellPrice; if (buyPrice == 0) { @@ -712,11 +712,11 @@ void AuctionBotSeller::SetPricesOfItem(ItemTemplate const* itemProto, SellerConf buyPrice = sellPrice * GetSellModifier(itemProto); else { - uint32 divisor = ((itemProto->Class == 2 || itemProto->Class == 4) ? 284 : 80); - uint32 tempLevel = (itemProto->ItemLevel == 0 ? 1 : itemProto->ItemLevel); - uint32 tempQuality = (itemProto->Quality == 0 ? 1 : itemProto->Quality); + float divisor = ((itemProto->Class == ITEM_CLASS_WEAPON || itemProto->Class == ITEM_CLASS_ARMOR) ? 284.0f : 80.0f); + float tempLevel = (itemProto->ItemLevel == 0 ? 1.0f : itemProto->ItemLevel); + float tempQuality = (itemProto->Quality == 0 ? 1.0f : itemProto->Quality); - buyPrice = tempLevel * tempQuality * GetBuyModifier(itemProto)* tempLevel / divisor; + buyPrice = tempLevel * tempQuality * static_cast<float>(GetBuyModifier(itemProto))* tempLevel / divisor; } } @@ -726,14 +726,15 @@ void AuctionBotSeller::SetPricesOfItem(ItemTemplate const* itemProto, SellerConf if (sAuctionBotConfig->GetConfig(CONFIG_AHBOT_BUYPRICE_SELLER)) buyPrice = sellPrice; - uint32 basePrice = (buyPrice * stackCount * priceRatio) / (itemProto->Class == 6 ? 200 : itemProto->BuyCount) / 100; - uint32 range = basePrice * 0.04; + float basePriceFloat = (buyPrice * stackCount * priceRatio) / (itemProto->Class == 6 ? 200.0f : static_cast<float>(itemProto->BuyCount)) / 100.0f; + float range = basePriceFloat * 0.04f; - buyp = urand(basePrice - range, basePrice + range) + 1; - - basePrice = buyp * .5; + buyp = static_cast<uint32>(frand(basePriceFloat - range, basePriceFloat + range) + 0.5f); + if (buyp == 0) + buyp = 1; + uint32 basePrice = buyp * .5; range = buyp * .4; - bidp = urand(basePrice - range, basePrice + range) + 1; + bidp = urand(static_cast<uint32>(basePrice - range + 0.5f), static_cast<uint32>(basePrice + range + 0.5f)) + 1; } // Determines the stack size to use for the item diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.h b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.h index dd82b0f3dda..3e6f263707f 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.h @@ -19,7 +19,7 @@ #define AUCTION_HOUSE_BOT_SELLER_H #include "Define.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" #include "AuctionHouseBot.h" struct ItemToSell @@ -115,7 +115,7 @@ private: // This class handle all Selling method // (holder of AHB_Seller_Config data for each auction house type) -class AuctionBotSeller : public AuctionBotAgent +class TC_GAME_API AuctionBotSeller : public AuctionBotAgent { public: typedef std::vector<uint32> ItemPool; diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index 34326d09e2f..f44099f6037 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -285,7 +285,7 @@ void Battlefield::InitStalker(uint32 entry, Position const& pos) if (Creature* creature = SpawnCreature(entry, pos, TEAM_NEUTRAL)) StalkerGuid = creature->GetGUID(); else - TC_LOG_ERROR("bg.battlefield", "Battlefield::InitStalker: could not spawn Stalker (Creature entry %u), zone messeges will be un-available", entry); + TC_LOG_ERROR("bg.battlefield", "Battlefield::InitStalker: Could not spawn Stalker (Creature entry %u), zone messages will be unavailable!", entry); } void Battlefield::KickAfkPlayers() @@ -544,10 +544,10 @@ BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const if (BfGraveyard* graveyard = m_GraveyardList.at(id)) return graveyard; else - TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u not existed", id); + TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u does not exist.", id); } else - TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u cant be found", id); + TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u could not be found.", id); return NULL; } @@ -765,7 +765,7 @@ Creature* Battlefield::SpawnCreature(uint32 entry, float x, float y, float z, fl Map* map = sMapMgr->CreateBaseMap(m_MapId); if (!map) { - TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u map not found", entry); + TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u, map not found.", entry); return nullptr; } @@ -782,7 +782,7 @@ Creature* Battlefield::SpawnCreature(uint32 entry, float x, float y, float z, fl CreatureTemplate const* cinfo = sObjectMgr->GetCreatureTemplate(entry); if (!cinfo) { - TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: entry %u does not exist.", entry); + TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Entry %u does not exist.", entry); return nullptr; } @@ -797,18 +797,21 @@ Creature* Battlefield::SpawnCreature(uint32 entry, float x, float y, float z, fl GameObject* Battlefield::SpawnGameObject(uint32 entry, float x, float y, float z, float o) { // Get map object - Map* map = sMapMgr->CreateBaseMap(571); // *vomits* + Map* map = sMapMgr->CreateBaseMap(m_MapId); if (!map) return 0; + // Calculate rotation + G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(o, 0.f, 0.f); + // Create gameobject GameObject* go = new GameObject; - if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, PHASEMASK_NORMAL, x, y, z, o, 0, 0, 0, 0, 100, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, PHASEMASK_NORMAL, Position(x, y, z, o), rot, 255, GO_STATE_READY)) { - TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Gameobject template %u not found in database! Battlefield not created!", entry); - TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Cannot create gameobject template %u! Battlefield not created!", entry); + TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Gameobject template %u could not be found in the database! Battlefield has not been created!", entry); + TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Could not create gameobject template %u! Battlefield has not been created!", entry); delete go; - return NULL; + return nullptr; } // Add to world @@ -907,7 +910,7 @@ bool BfCapturePoint::SetCapturePointData(GameObject* capturePoint) GameObjectTemplate const* goinfo = capturePoint->GetGOInfo(); if (goinfo->type != GAMEOBJECT_TYPE_CAPTURE_POINT) { - TC_LOG_ERROR("misc", "OutdoorPvP: GO %u is not capture point!", capturePoint->GetEntry()); + TC_LOG_ERROR("misc", "OutdoorPvP: GO %u is not a capture point!", capturePoint->GetEntry()); return false; } diff --git a/src/server/game/Battlefield/Battlefield.h b/src/server/game/Battlefield/Battlefield.h index ade3e8c9699..6968e31c7bd 100644 --- a/src/server/game/Battlefield/Battlefield.h +++ b/src/server/game/Battlefield/Battlefield.h @@ -67,7 +67,7 @@ class BfGraveyard; typedef std::vector<BfGraveyard*> GraveyardVect; typedef std::map<ObjectGuid, time_t> PlayerTimerMap; -class BfCapturePoint +class TC_GAME_API BfCapturePoint { public: BfCapturePoint(Battlefield* bf); @@ -135,7 +135,7 @@ class BfCapturePoint ObjectGuid m_capturePointGUID; }; -class BfGraveyard +class TC_GAME_API BfGraveyard { public: BfGraveyard(Battlefield* Bf); @@ -182,7 +182,7 @@ class BfGraveyard Battlefield* m_Bf; }; -class Battlefield : public ZoneScript +class TC_GAME_API Battlefield : public ZoneScript { friend class BattlefieldMgr; diff --git a/src/server/game/Battlefield/BattlefieldMgr.cpp b/src/server/game/Battlefield/BattlefieldMgr.cpp index e4c10d64682..1df87fe1d6f 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.cpp +++ b/src/server/game/Battlefield/BattlefieldMgr.cpp @@ -32,6 +32,12 @@ BattlefieldMgr::~BattlefieldMgr() _battlefieldMap.clear(); } +BattlefieldMgr* BattlefieldMgr::instance() +{ + static BattlefieldMgr instance; + return &instance; +} + void BattlefieldMgr::InitBattlefield() { Battlefield* wg = new BattlefieldWG(); diff --git a/src/server/game/Battlefield/BattlefieldMgr.h b/src/server/game/Battlefield/BattlefieldMgr.h index fabb33ae359..2f2af12927e 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.h +++ b/src/server/game/Battlefield/BattlefieldMgr.h @@ -24,14 +24,10 @@ class Player; class ZoneScript; // class to handle player enter / leave / areatrigger / GO use events -class BattlefieldMgr +class TC_GAME_API BattlefieldMgr { public: - static BattlefieldMgr* instance() - { - static BattlefieldMgr instance; - return &instance; - } + static BattlefieldMgr* instance(); // create battlefield events void InitBattlefield(); diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.h b/src/server/game/Battlefield/Zones/BattlefieldWG.h index e5cc392cef3..52789d38d8e 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.h +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.h @@ -266,7 +266,7 @@ class WintergraspCapturePoint : public BfCapturePoint * WinterGrasp Battlefield * * ######################### */ -class BattlefieldWG : public Battlefield +class TC_GAME_API BattlefieldWG : public Battlefield { public: ~BattlefieldWG(); @@ -1098,7 +1098,7 @@ StaticWintergraspWorkshopInfo const WorkshopData[WG_MAX_WORKSHOP] = // ******************************************************************** // Structure for different buildings that can be destroyed during battle -struct BfWGGameObjectBuilding +struct TC_GAME_API BfWGGameObjectBuilding { private: // WG object @@ -1150,7 +1150,7 @@ public: }; // Structure for the 6 workshop -struct WintergraspWorkshop +struct TC_GAME_API WintergraspWorkshop { private: BattlefieldWG* _wg; // Pointer to wintergrasp diff --git a/src/server/game/Battlegrounds/Arena.h b/src/server/game/Battlegrounds/Arena.h index 863f1fc8c6f..1fe99f1f414 100644 --- a/src/server/game/Battlegrounds/Arena.h +++ b/src/server/game/Battlegrounds/Arena.h @@ -36,7 +36,7 @@ enum ArenaWorldStates ARENA_WORLD_STATE_ALIVE_PLAYERS_GOLD = 3601 }; -class Arena : public Battleground +class TC_GAME_API Arena : public Battleground { protected: Arena(); diff --git a/src/server/game/Battlegrounds/ArenaScore.h b/src/server/game/Battlegrounds/ArenaScore.h index c2d9d18c00b..9427a108565 100644 --- a/src/server/game/Battlegrounds/ArenaScore.h +++ b/src/server/game/Battlegrounds/ArenaScore.h @@ -21,7 +21,7 @@ #include "BattlegroundScore.h" #include "SharedDefines.h" -struct ArenaScore : public BattlegroundScore +struct TC_GAME_API ArenaScore : public BattlegroundScore { friend class Arena; @@ -56,7 +56,7 @@ struct ArenaScore : public BattlegroundScore uint8 TeamId; // BattlegroundTeamId }; -struct ArenaTeamScore +struct TC_GAME_API ArenaTeamScore { friend class Arena; friend class Battleground; diff --git a/src/server/game/Battlegrounds/ArenaTeam.h b/src/server/game/Battlegrounds/ArenaTeam.h index f27c3761bde..7e9f490bff9 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.h +++ b/src/server/game/Battlegrounds/ArenaTeam.h @@ -85,7 +85,7 @@ enum ArenaTeamTypes ARENA_TEAM_5v5 = 5 }; -struct ArenaTeamMember +struct TC_GAME_API ArenaTeamMember { ObjectGuid Guid; std::string Name; @@ -113,7 +113,7 @@ struct ArenaTeamStats #define MAX_ARENA_SLOT 3 // 0..2 slots -class ArenaTeam +class TC_GAME_API ArenaTeam { public: ArenaTeam(); diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp index b838131fd03..37e26d7e448 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp @@ -35,6 +35,12 @@ ArenaTeamMgr::~ArenaTeamMgr() delete itr->second; } +ArenaTeamMgr* ArenaTeamMgr::instance() +{ + static ArenaTeamMgr instance; + return &instance; +} + // Arena teams collection ArenaTeam* ArenaTeamMgr::GetArenaTeamById(uint32 arenaTeamId) const { @@ -93,7 +99,7 @@ void ArenaTeamMgr::LoadArenaTeams() uint32 oldMSTime = getMSTime(); // Clean out the trash before loading anything - CharacterDatabase.Execute("DELETE FROM arena_team_member WHERE arenaTeamId NOT IN (SELECT arenaTeamId FROM arena_team)"); // One-time query + CharacterDatabase.DirectExecute("DELETE FROM arena_team_member WHERE arenaTeamId NOT IN (SELECT arenaTeamId FROM arena_team)"); // One-time query // 0 1 2 3 4 5 6 7 8 QueryResult result = CharacterDatabase.Query("SELECT arenaTeamId, name, captainGuid, type, backgroundColor, emblemStyle, emblemColor, borderStyle, borderColor, " diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.h b/src/server/game/Battlegrounds/ArenaTeamMgr.h index 432a4ff598f..7f6800bd71b 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.h +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.h @@ -20,18 +20,14 @@ #include "ArenaTeam.h" -class ArenaTeamMgr +class TC_GAME_API ArenaTeamMgr { private: ArenaTeamMgr(); ~ArenaTeamMgr(); public: - static ArenaTeamMgr* instance() - { - static ArenaTeamMgr instance; - return &instance; - } + static ArenaTeamMgr* instance(); typedef std::unordered_map<uint32, ArenaTeam*> ArenaTeamContainer; diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index 100e2e6c7cc..2e66c587e15 100644 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -283,8 +283,12 @@ inline void Battleground::_CheckSafePositions(uint32 diff) m_ValidStartPositionTimer = 0; for (BattlegroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr) + { if (Player* player = ObjectAccessor::FindPlayer(itr->first)) { + if (player->IsGameMaster()) + continue; + Position pos = player->GetPosition(); Position const* startPos = GetTeamStartPosition(Battleground::GetTeamIndexByTeamId(player->GetBGTeam())); if (pos.GetExactDistSq(startPos) > maxDist) @@ -293,6 +297,7 @@ inline void Battleground::_CheckSafePositions(uint32 diff) player->TeleportTo(GetMapId(), startPos->GetPositionX(), startPos->GetPositionY(), startPos->GetPositionZ(), startPos->GetOrientation()); } } + } } } @@ -1345,12 +1350,22 @@ bool Battleground::AddObject(uint32 type, uint32 entry, float x, float y, float Map* map = FindBgMap(); if (!map) return false; + + G3D::Quat rot(rotation0, rotation1, rotation2, rotation3); + // Temporally add safety check for bad spawns and send log (object rotations need to be rechecked in sniff) + if (!rotation0 && !rotation1 && !rotation2 && !rotation3) + { + TC_LOG_DEBUG("bg.battleground", "Battleground::AddObject: gameoobject [entry: %u, object type: %u] for BG (map: %u) has zeroed rotation fields, " + "orientation used temporally, but please fix the spawn", entry, type, m_MapId); + + rot = G3D::Matrix3::fromEulerAnglesZYX(o, 0.f, 0.f); + } + // Must be created this way, adding to godatamap would add it to the base map of the instance // and when loading it (in go::LoadFromDB()), a new guid would be assigned to the object, and a new object would be created // So we must create it specific for this instance GameObject* go = new GameObject; - if (!go->Create(GetBgMap()->GenerateLowGuid<HighGuid::GameObject>(), entry, GetBgMap(), - PHASEMASK_NORMAL, x, y, z, o, rotation0, rotation1, rotation2, rotation3, 100, goState)) + if (!go->Create(GetBgMap()->GenerateLowGuid<HighGuid::GameObject>(), entry, GetBgMap(), PHASEMASK_NORMAL, Position(x, y, z, o), rot, 255, goState)) { TC_LOG_ERROR("bg.battleground", "Battleground::AddObject: cannot create gameobject (entry: %u) for BG (map: %u, instance id: %u)!", entry, m_MapId, m_InstanceID); diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index 03f138a5a8b..bb6ae360536 100644 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -221,7 +221,7 @@ This class is used to: 3. some certain cases, same for all battlegrounds 4. It has properties same for all battlegrounds */ -class Battleground +class TC_GAME_API Battleground { public: Battleground(); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 062d4702d43..683547ef3fc 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -76,6 +76,12 @@ void BattlegroundMgr::DeleteAllBattlegrounds() bgDataStore.clear(); } +BattlegroundMgr* BattlegroundMgr::instance() +{ + static BattlegroundMgr instance; + return &instance; +} + // used to update running battlegrounds, and delete finished ones void BattlegroundMgr::Update(uint32 diff) { @@ -536,7 +542,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(bgTypeId); if (!bl) { - TC_LOG_ERROR("bg.battleground", "Battleground ID %u not found in BattlemasterList.dbc. Battleground not created.", bgTypeId); + TC_LOG_ERROR("bg.battleground", "Battleground ID %u could not be found in BattlemasterList.dbc. The battleground was not created.", bgTypeId); continue; } @@ -554,14 +560,14 @@ void BattlegroundMgr::LoadBattlegroundTemplates() if (bgTemplate.MaxPlayersPerTeam == 0 || bgTemplate.MinPlayersPerTeam > bgTemplate.MaxPlayersPerTeam) { - TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u has bad values for MinPlayersPerTeam (%u) and MaxPlayersPerTeam(%u)", + TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u contains bad values for MinPlayersPerTeam (%u) and MaxPlayersPerTeam(%u).", bgTemplate.Id, bgTemplate.MinPlayersPerTeam, bgTemplate.MaxPlayersPerTeam); continue; } if (bgTemplate.MinLevel == 0 || bgTemplate.MaxLevel == 0 || bgTemplate.MinLevel > bgTemplate.MaxLevel) { - TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u has bad values for MinLevel (%u) and MaxLevel (%u)", + TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u contains bad values for MinLevel (%u) and MaxLevel (%u).", bgTemplate.Id, bgTemplate.MinLevel, bgTemplate.MaxLevel); continue; } @@ -575,7 +581,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() } else { - TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u has non-existed WorldSafeLocs.dbc id %u in field `AllianceStartLoc`. BG not created.", bgTemplate.Id, startId); + TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u contains a non-existing WorldSafeLocs.dbc id %u in field `AllianceStartLoc`. BG not created.", bgTemplate.Id, startId); continue; } @@ -586,7 +592,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() } else { - TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u has non-existed WorldSafeLocs.dbc id %u in field `HordeStartLoc`. BG not created.", bgTemplate.Id, startId); + TC_LOG_ERROR("sql.sql", "Table `battleground_template` for id %u contains a non-existing WorldSafeLocs.dbc id %u in field `HordeStartLoc`. BG not created.", bgTemplate.Id, startId); continue; } } @@ -788,7 +794,7 @@ BattlegroundTypeId BattlegroundMgr::BGTemplateId(BattlegroundQueueTypeId bgQueue case BATTLEGROUND_QUEUE_5v5: return BATTLEGROUND_AA; default: - return BattlegroundTypeId(0); // used for unknown template (it existed and do nothing) + return BattlegroundTypeId(0); // used for unknown template (it exists and does nothing) } } @@ -892,7 +898,7 @@ void BattlegroundMgr::LoadBattleMastersEntry() uint32 bgTypeId = fields[1].GetUInt32(); if (!sBattlemasterListStore.LookupEntry(bgTypeId)) { - TC_LOG_ERROR("sql.sql", "Table `battlemaster_entry` contain entry %u for not existed battleground type %u, ignored.", entry, bgTypeId); + TC_LOG_ERROR("sql.sql", "Table `battlemaster_entry` contains entry %u for a non-existing battleground type %u, ignored.", entry, bgTypeId); continue; } @@ -912,7 +918,7 @@ void BattlegroundMgr::CheckBattleMasters() { if ((itr->second.npcflag & UNIT_NPC_FLAG_BATTLEMASTER) && mBattleMastersMap.find(itr->second.Entry) == mBattleMastersMap.end()) { - TC_LOG_ERROR("sql.sql", "CreatureTemplate (Entry: %u) has UNIT_NPC_FLAG_BATTLEMASTER but no data in `battlemaster_entry` table. Removing flag!", itr->second.Entry); + TC_LOG_ERROR("sql.sql", "Creature_Template Entry: %u has UNIT_NPC_FLAG_BATTLEMASTER, but no data in the `battlemaster_entry` table. Removing flag.", itr->second.Entry); const_cast<CreatureTemplate*>(&itr->second)->npcflag &= ~UNIT_NPC_FLAG_BATTLEMASTER; } } diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index 595745e53fb..dbba964d4b3 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -55,18 +55,14 @@ struct BattlegroundTemplate bool IsArena() const { return BattlemasterEntry->type == MAP_ARENA; } }; -class BattlegroundMgr +class TC_GAME_API BattlegroundMgr { private: BattlegroundMgr(); ~BattlegroundMgr(); public: - static BattlegroundMgr* instance() - { - static BattlegroundMgr instance; - return &instance; - } + static BattlegroundMgr* instance(); void Update(uint32 diff); diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index 34588c7e380..796afe472fe 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -161,9 +161,9 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, Battlegr //announce world (this don't need mutex) if (isRated && sWorld->getBoolConfig(CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE)) { - ArenaTeam* Team = sArenaTeamMgr->GetArenaTeamById(arenateamid); - if (Team) - sWorld->SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN, Team->GetName().c_str(), ginfo->ArenaType, ginfo->ArenaType, ginfo->ArenaTeamRating); + ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(arenateamid); + if (team) + sWorld->SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_JOIN, team->GetName().c_str(), ginfo->ArenaType, ginfo->ArenaType, ginfo->ArenaTeamRating); } //add players from group to ginfo @@ -354,8 +354,8 @@ void BattlegroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) // announce to world if arena team left queue for rated match, show only once if (group->ArenaType && group->IsRated && group->Players.empty() && sWorld->getBoolConfig(CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE)) - if (ArenaTeam* Team = sArenaTeamMgr->GetArenaTeamById(group->ArenaTeamId)) - sWorld->SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, Team->GetName().c_str(), group->ArenaType, group->ArenaType, group->ArenaTeamRating); + if (ArenaTeam* team = sArenaTeamMgr->GetArenaTeamById(group->ArenaTeamId)) + sWorld->SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, team->GetName().c_str(), group->ArenaType, group->ArenaType, group->ArenaTeamRating); // if player leaves queue and he is invited to rated arena match, then he have to lose if (group->IsInvitedToBGInstanceGUID && group->IsRated && decreaseInvitedCount) diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.h b/src/server/game/Battlegrounds/BattlegroundQueue.h index 31f108053d9..f56ccb9bdbf 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.h +++ b/src/server/game/Battlegrounds/BattlegroundQueue.h @@ -72,7 +72,7 @@ enum BattlegroundQueueInvitationType }; class Battleground; -class BattlegroundQueue +class TC_GAME_API BattlegroundQueue { public: BattlegroundQueue(); @@ -142,7 +142,7 @@ class BattlegroundQueue This class is used to invite player to BG again, when minute lasts from his first invitation it is capable to solve all possibilities */ -class BGQueueInviteEvent : public BasicEvent +class TC_GAME_API BGQueueInviteEvent : public BasicEvent { public: BGQueueInviteEvent(ObjectGuid pl_guid, uint32 BgInstanceGUID, BattlegroundTypeId BgTypeId, uint8 arenaType, uint32 removeTime) : @@ -165,7 +165,7 @@ class BGQueueInviteEvent : public BasicEvent We must store removeInvite time in case player left queue and joined and is invited again We must store bgQueueTypeId, because battleground can be deleted already, when player entered it */ -class BGQueueRemoveEvent : public BasicEvent +class TC_GAME_API BGQueueRemoveEvent : public BasicEvent { public: BGQueueRemoveEvent(ObjectGuid pl_guid, uint32 bgInstanceGUID, BattlegroundTypeId BgTypeId, BattlegroundQueueTypeId bgQueueTypeId, uint32 removeTime) diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 626bcacbf27..e52106a8efe 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -171,7 +171,7 @@ void BattlegroundEY::CheckSomeoneJoinedPoint() Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[EY_POINTS_MAX][j]); if (!player) { - TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneJoinedPoint: Player (%s) not found!", m_PlayersNearPoint[EY_POINTS_MAX][j].ToString().c_str()); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneJoinedPoint: Player (%s) could not be found!", m_PlayersNearPoint[EY_POINTS_MAX][j].ToString().c_str()); ++j; continue; } @@ -212,8 +212,8 @@ void BattlegroundEY::CheckSomeoneLeftPoint() Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[i][j]); if (!player) { - TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneLeftPoint Player (%s) not found!", m_PlayersNearPoint[i][j].ToString().c_str()); - //move not existed player to "free space" - this will cause many error showing in log, but it is a very important bug + TC_LOG_ERROR("bg.battleground", "BattlegroundEY:CheckSomeoneLeftPoint Player (%s) could not be found!", m_PlayersNearPoint[i][j].ToString().c_str()); + //move non-existing players to "free space" - this will cause many errors showing in log, but it is a very important bug m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]); m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j); continue; @@ -498,7 +498,7 @@ bool BattlegroundEY::SetupBattleground() || !AddObject(BG_EY_OBJECT_TOWER_CAP_MAGE_TOWER, BG_OBJECT_HU_TOWER_CAP_EY_ENTRY, 2282.121582f, 1760.006958f, 1189.707153f, 1.919862f, 0, 0, 0.819152f, 0.573576f, RESPAWN_ONE_DAY) ) { - TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn some object Battleground not created!"); + TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn some objects. The battleground was not created."); return false; } @@ -515,21 +515,21 @@ bool BattlegroundEY::SetupBattleground() || !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 1, Buff_Entries[1], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY) || !AddObject(BG_EY_OBJECT_SPEEDBUFF_FEL_REAVER + i * 3 + 2, Buff_Entries[2], at->x, at->y, at->z, 0.907571f, 0, 0, 0.438371f, 0.898794f, RESPAWN_ONE_DAY) ) - TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Cannot spawn buff"); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Could not spawn Speedbuff Fel Reaver."); } WorldSafeLocsEntry const* sg = NULL; sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_ALLIANCE); if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_ALLIANCE, sg->x, sg->y, sg->z, 3.124139f, TEAM_ALLIANCE)) { - TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide! Battleground not created!"); + TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide. The battleground was not created."); return false; } sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_HORDE); if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_HORDE, sg->x, sg->y, sg->z, 3.193953f, TEAM_HORDE)) { - TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide! Battleground not created!"); + TC_LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guide. The battleground was not created."); return false; } @@ -595,7 +595,7 @@ void BattlegroundEY::RespawnFlagAfterDrop() if (obj) obj->Delete(); else - TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Unknown dropped flag (%s)", GetDroppedFlagGUID().ToString().c_str()); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Unknown dropped flag (%s).", GetDroppedFlagGUID().ToString().c_str()); SetDroppedFlagGUID(ObjectGuid::Empty); } @@ -767,7 +767,7 @@ void BattlegroundEY::EventTeamCapturedPoint(Player* player, uint32 Point) WorldSafeLocsEntry const* sg = NULL; sg = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[Point].GraveYardId); if (!sg || !AddSpiritGuide(Point, sg->x, sg->y, sg->z, 3.124139f, GetTeamIndexByTeamId(Team))) - TC_LOG_ERROR("bg.battleground", "BatteGroundEY: Failed to spawn spirit guide! point: %u, team: %u, graveyard_id: %u", + TC_LOG_ERROR("bg.battleground", "BatteGroundEY: Failed to spawn spirit guide. point: %u, team: %u, graveyard_id: %u", Point, Team, m_CapturingPointTypes[Point].GraveYardId); // SpawnBGCreature(Point, RESPAWN_IMMEDIATELY); @@ -917,7 +917,7 @@ WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) if (!entry) { - TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Not found the main team graveyard. Graveyard system isn't working!"); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY: The main team graveyard could not be found. The graveyard system will not be operational!"); return NULL; } @@ -934,7 +934,7 @@ WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) { entry = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[i].GraveYardId); if (!entry) - TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Not found graveyard: %u", m_CapturingPointTypes[i].GraveYardId); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Graveyard %u could not be found.", m_CapturingPointTypes[i].GraveYardId); else { distance = (entry->x - plr_x)*(entry->x - plr_x) + (entry->y - plr_y)*(entry->y - plr_y) + (entry->z - plr_z)*(entry->z - plr_z); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp index 52e0deaf86f..8c144cbc8be 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp @@ -142,8 +142,8 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) { if (siege->IsAlive()) { - if (siege->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_UNK_14|UNIT_FLAG_IMMUNE_TO_PC)) - // following sniffs the vehicle always has UNIT_FLAG_UNK_14 + if (siege->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_CANNOT_SWIM|UNIT_FLAG_IMMUNE_TO_PC)) + // following sniffs the vehicle always has UNIT_FLAG_CANNOT_SWIM siege->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_IMMUNE_TO_PC); else siege->SetHealth(siege->GetMaxHealth()); @@ -762,7 +762,7 @@ void BattlegroundIC::HandleCapturedNodes(ICNodePoint* node, bool recapture) if (Creature* siegeEngine = GetBGCreature(siegeType)) { - siegeEngine->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_UNK_14|UNIT_FLAG_IMMUNE_TO_PC); + siegeEngine->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_CANNOT_SWIM|UNIT_FLAG_IMMUNE_TO_PC); siegeEngine->setFaction(BG_IC_Factions[(node->faction == TEAM_ALLIANCE ? 0 : 1)]); } } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp index 1942ac9d648..450f5cd9144 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp @@ -151,8 +151,8 @@ bool BattlegroundSA::ResetObjs() } // MAD props for Kiper for discovering those values - 4 hours of his work. - GetBGObject(BG_SA_BOAT_ONE)->UpdateRotationFields(1.0f, 0.0002f); - GetBGObject(BG_SA_BOAT_TWO)->UpdateRotationFields(1.0f, 0.00001f); + GetBGObject(BG_SA_BOAT_ONE)->SetParentRotation(G3D::Quat(0.f, 0.f, 1.0f, 0.0002f)); + GetBGObject(BG_SA_BOAT_TWO)->SetParentRotation(G3D::Quat(0.f, 0.f, 1.0f, 0.00001f)); SpawnBGObject(BG_SA_BOAT_ONE, RESPAWN_IMMEDIATELY); SpawnBGObject(BG_SA_BOAT_TWO, RESPAWN_IMMEDIATELY); diff --git a/src/server/game/CMakeLists.txt b/src/server/game/CMakeLists.txt index aae5b4874d8..239e59d6dbb 100644 --- a/src/server/game/CMakeLists.txt +++ b/src/server/game/CMakeLists.txt @@ -8,206 +8,72 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -file(GLOB_RECURSE sources_Accounts Accounts/*.cpp Accounts/*.h) -file(GLOB_RECURSE sources_Achievements Achievements/*.cpp Achievements/*.h) -file(GLOB_RECURSE sources_Addons Addons/*.cpp Addons/*.h) -file(GLOB_RECURSE sources_AI AI/*.cpp AI/*.h) -file(GLOB_RECURSE sources_AuctionHouse AuctionHouse/*.cpp AuctionHouse/*.h) -file(GLOB_RECURSE sources_AuctionHouseBot AuctionHouseBot/*.cpp AuctionHouseBot/*.h) -file(GLOB_RECURSE sources_Battlefield Battlefield/*.cpp Battlefield/*.h) -file(GLOB_RECURSE sources_Battlegrounds Battlegrounds/*.cpp Battlegrounds/*.h) -file(GLOB_RECURSE sources_Calendar Calendar/*.cpp Calendar/*.h) -file(GLOB_RECURSE sources_Chat Chat/*.cpp Chat/*.h) -file(GLOB_RECURSE sources_Combat Combat/*.cpp Combat/*.h) -file(GLOB_RECURSE sources_Conditions Conditions/*.cpp Conditions/*.h) -file(GLOB_RECURSE sources_DataStores DataStores/*.cpp DataStores/*.h) -file(GLOB_RECURSE sources_DungeonFinding DungeonFinding/*.cpp DungeonFinding/*.h) -file(GLOB_RECURSE sources_Entities Entities/*.cpp Entities/*.h) -file(GLOB_RECURSE sources_Events Events/*.cpp Events/*.h) -file(GLOB_RECURSE sources_Globals Globals/*.cpp Globals/*.h) -file(GLOB_RECURSE sources_Grids Grids/*.cpp Grids/*.h) -file(GLOB_RECURSE sources_Groups Groups/*.cpp Groups/*.h) -file(GLOB_RECURSE sources_Guilds Guilds/*.cpp Guilds/*.h) -file(GLOB_RECURSE sources_Handlers Handlers/*.cpp Handlers/*.h) -file(GLOB_RECURSE sources_Instances Instances/*.cpp Instances/*.h) -file(GLOB_RECURSE sources_Loot Loot/*.cpp Loot/*.h) -file(GLOB_RECURSE sources_Mails Mails/*.cpp Mails/*.h) -file(GLOB_RECURSE sources_Maps Maps/*.cpp Maps/*.h) -file(GLOB_RECURSE sources_Miscellaneous Miscellaneous/*.cpp Miscellaneous/*.h) -file(GLOB_RECURSE sources_Movement Movement/*.cpp Movement/*.h) -file(GLOB_RECURSE sources_OutdoorPvP OutdoorPvP/*.cpp OutdoorPvP/*.h) -file(GLOB_RECURSE sources_Pools Pools/*.cpp Pools/*.h) -file(GLOB_RECURSE sources_Quests Quests/*.cpp Quests/*.h) -file(GLOB_RECURSE sources_Reputation Reputation/*.cpp Reputation/*.h) -file(GLOB_RECURSE sources_Scripting Scripting/*.cpp Scripting/*.h) -file(GLOB_RECURSE sources_Server Server/*.cpp Server/*.h) -file(GLOB_RECURSE sources_Skills Skills/*.cpp Skills/*.h) -file(GLOB_RECURSE sources_Spells Spells/*.cpp Spells/*.h) -file(GLOB_RECURSE sources_Texts Texts/*.cpp Texts/*.h) -file(GLOB_RECURSE sources_Tools Tools/*.cpp Tools/*.h) -file(GLOB_RECURSE sources_Tickets Tickets/*.cpp Tickets/*.h) -file(GLOB_RECURSE sources_Warden Warden/*.cpp Warden/*.h) -file(GLOB_RECURSE sources_Weather Weather/*.cpp Weather/*.h) -file(GLOB_RECURSE sources_World World/*.cpp World/*.h) - -# Create game-libary +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) if (USE_COREPCH) - set(game_STAT_PCH_HDR PrecompiledHeaders/gamePCH.h) - set(game_STAT_PCH_SRC PrecompiledHeaders/gamePCH.cpp) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/gamePCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/gamePCH.cpp) endif () -set(game_STAT_SRCS - ${game_STAT_SRCS} - ${sources_Accounts} - ${sources_Achievements} - ${sources_Addons} - ${sources_AI} - ${sources_AuctionHouse} - ${sources_AuctionHouseBot} - ${sources_Battlefield} - ${sources_Battlegrounds} - ${sources_Calendar} - ${sources_Chat} - ${sources_Combat} - ${sources_Conditions} - ${sources_DataStores} - ${sources_DungeonFinding} - ${sources_Entities} - ${sources_Events} - ${sources_Globals} - ${sources_Grids} - ${sources_Groups} - ${sources_Guilds} - ${sources_Handlers} - ${sources_Instances} - ${sources_Loot} - ${sources_Mails} - ${sources_Maps} - ${sources_Miscellaneous} - ${sources_Movement} - ${sources_OutdoorPvP} - ${sources_Pools} - ${sources_Quests} - ${sources_Reputation} - ${sources_Scripting} - ${sources_Server} - ${sources_Skills} - ${sources_Spells} - ${sources_Texts} - ${sources_Tools} - ${sources_Tickets} - ${sources_Warden} - ${sources_Weather} - ${sources_World} -) +GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/Accounts - ${CMAKE_CURRENT_SOURCE_DIR}/Achievements - ${CMAKE_CURRENT_SOURCE_DIR}/Addons - ${CMAKE_CURRENT_SOURCE_DIR}/AI - ${CMAKE_CURRENT_SOURCE_DIR}/AI/CoreAI - ${CMAKE_CURRENT_SOURCE_DIR}/AI/ScriptedAI - ${CMAKE_CURRENT_SOURCE_DIR}/AI/SmartScripts - ${CMAKE_CURRENT_SOURCE_DIR}/AuctionHouse - ${CMAKE_CURRENT_SOURCE_DIR}/AuctionHouseBot - ${CMAKE_CURRENT_SOURCE_DIR}/Battlefield - ${CMAKE_CURRENT_SOURCE_DIR}/Battlefield/Zones - ${CMAKE_CURRENT_SOURCE_DIR}/Battlegrounds - ${CMAKE_CURRENT_SOURCE_DIR}/Battlegrounds/Zones - ${CMAKE_CURRENT_SOURCE_DIR}/Calendar - ${CMAKE_CURRENT_SOURCE_DIR}/Chat - ${CMAKE_CURRENT_SOURCE_DIR}/Chat/Channels - ${CMAKE_CURRENT_SOURCE_DIR}/Combat - ${CMAKE_CURRENT_SOURCE_DIR}/Conditions - ${CMAKE_CURRENT_SOURCE_DIR}/DataStores - ${CMAKE_CURRENT_SOURCE_DIR}/DungeonFinding - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Corpse - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Creature - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/DynamicObject - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/GameObject - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Item - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Item/Container - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Object - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Object/Updates - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Pet - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Player - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Totem - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Transport - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Unit - ${CMAKE_CURRENT_SOURCE_DIR}/Entities/Vehicle - ${CMAKE_CURRENT_SOURCE_DIR}/Events - ${CMAKE_CURRENT_SOURCE_DIR}/Globals - ${CMAKE_CURRENT_SOURCE_DIR}/Grids - ${CMAKE_CURRENT_SOURCE_DIR}/Grids/Cells - ${CMAKE_CURRENT_SOURCE_DIR}/Grids/Notifiers - ${CMAKE_CURRENT_SOURCE_DIR}/Groups - ${CMAKE_CURRENT_SOURCE_DIR}/Guilds - ${CMAKE_CURRENT_SOURCE_DIR}/Handlers - ${CMAKE_CURRENT_SOURCE_DIR}/Instances - ${CMAKE_CURRENT_SOURCE_DIR}/Loot - ${CMAKE_CURRENT_SOURCE_DIR}/Mails - ${CMAKE_CURRENT_SOURCE_DIR}/Maps - ${CMAKE_CURRENT_SOURCE_DIR}/Miscellaneous - ${CMAKE_CURRENT_SOURCE_DIR}/Movement - ${CMAKE_CURRENT_SOURCE_DIR}/Movement/MovementGenerators - ${CMAKE_CURRENT_SOURCE_DIR}/Movement/Spline - ${CMAKE_CURRENT_SOURCE_DIR}/Movement/Waypoints - ${CMAKE_CURRENT_SOURCE_DIR}/OutdoorPvP - ${CMAKE_CURRENT_SOURCE_DIR}/Pools - ${CMAKE_CURRENT_SOURCE_DIR}/Quests - ${CMAKE_CURRENT_SOURCE_DIR}/Reputation - ${CMAKE_CURRENT_SOURCE_DIR}/Scripting - ${CMAKE_CURRENT_SOURCE_DIR}/Server - ${CMAKE_CURRENT_SOURCE_DIR}/Server/Protocol - ${CMAKE_CURRENT_SOURCE_DIR}/Skills - ${CMAKE_CURRENT_SOURCE_DIR}/Spells - ${CMAKE_CURRENT_SOURCE_DIR}/Spells/Auras - ${CMAKE_CURRENT_SOURCE_DIR}/Texts - ${CMAKE_CURRENT_SOURCE_DIR}/Tickets - ${CMAKE_CURRENT_SOURCE_DIR}/Tools - ${CMAKE_CURRENT_SOURCE_DIR}/Warden - ${CMAKE_CURRENT_SOURCE_DIR}/Warden/Modules - ${CMAKE_CURRENT_SOURCE_DIR}/Weather - ${CMAKE_CURRENT_SOURCE_DIR}/World - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour/Include - ${CMAKE_SOURCE_DIR}/dep/zlib - ${CMAKE_SOURCE_DIR}/src/common - ${CMAKE_SOURCE_DIR}/src/common/Collision - ${CMAKE_SOURCE_DIR}/src/common/Collision/Management - ${CMAKE_SOURCE_DIR}/src/common/Collision/Maps - ${CMAKE_SOURCE_DIR}/src/common/Collision/Models - ${CMAKE_SOURCE_DIR}/src/common/Configuration - ${CMAKE_SOURCE_DIR}/src/common/Cryptography - ${CMAKE_SOURCE_DIR}/src/common/Cryptography/Authentication - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/database - ${CMAKE_SOURCE_DIR}/src/server/database/Database - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/shared/DataStores - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic/LinkedReference - ${CMAKE_SOURCE_DIR}/src/server/shared/Networking - ${CMAKE_SOURCE_DIR}/src/server/shared/Packets - ${MYSQL_INCLUDE_DIR} - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) +add_definitions(-DTRINITY_API_EXPORT_GAME) -GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) + +# Provide an interface target for the game project to allow +# dependent projects to build meanwhile. +add_library(game-interface INTERFACE) + +target_include_directories(game-interface + INTERFACE + ${PUBLIC_INCLUDES}) + +target_link_libraries(game-interface + INTERFACE + shared + Detour) + +add_library(game + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES}) + +target_include_directories(game + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +target_link_libraries(game + PUBLIC + game-interface + PRIVATE + efsw) + +set_target_properties(game + PROPERTIES + FOLDER + "server") -add_library(game STATIC - ${game_STAT_SRCS} - ${game_STAT_PCH_SRC} -) +if( BUILD_SHARED_LIBS ) + if( UNIX ) + install(TARGETS game + LIBRARY + DESTINATION lib) + elseif( WIN32 ) + install(TARGETS game + RUNTIME + DESTINATION "${CMAKE_INSTALL_PREFIX}") + endif() +endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(game ${game_STAT_PCH_HDR} ${game_STAT_PCH_SRC}) + add_cxx_pch(game ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif () diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 9d50b290c5e..b27aac7876a 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -45,6 +45,12 @@ CalendarMgr::~CalendarMgr() delete *itr2; } +CalendarMgr* CalendarMgr::instance() +{ + static CalendarMgr instance; + return &instance; +} + void CalendarMgr::LoadFromDB() { uint32 count = 0; diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index 59303a18324..c282e3e202c 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -126,7 +126,7 @@ enum CalendarError #define CALENDAR_MAX_GUILD_EVENTS 100 #define CALENDAR_MAX_INVITES 100 -struct CalendarInvite +struct TC_GAME_API CalendarInvite { public: CalendarInvite(CalendarInvite const& calendarInvite, uint64 inviteId, uint64 eventId) @@ -186,7 +186,7 @@ struct CalendarInvite std::string _text; }; -struct CalendarEvent +struct TC_GAME_API CalendarEvent { public: CalendarEvent(CalendarEvent const& calendarEvent, uint64 eventId) @@ -266,7 +266,7 @@ typedef std::vector<CalendarInvite*> CalendarInviteStore; typedef std::set<CalendarEvent*> CalendarEventStore; typedef std::map<uint64 /* eventId */, CalendarInviteStore > CalendarEventInviteStore; -class CalendarMgr +class TC_GAME_API CalendarMgr { private: CalendarMgr(); @@ -281,11 +281,7 @@ class CalendarMgr uint64 _maxInviteId; public: - static CalendarMgr* instance() - { - static CalendarMgr instance; - return &instance; - } + static CalendarMgr* instance(); void LoadFromDB(); diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 0875ceefff5..a34f0f4d9a2 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -25,66 +25,66 @@ #include "AccountMgr.h" #include "Player.h" -Channel::Channel(std::string const& name, uint32 channelId, uint32 team): - _announce(true), - _ownership(true), - _IsSaved(false), - _flags(0), +Channel::Channel(std::string const& name, uint32 channelId, uint32 team /*= 0*/): + _announceEnabled(true), + _ownershipEnabled(true), + _persistentChannel(false), + _channelFlags(0), _channelId(channelId), - _Team(team), - _ownerGUID(), - _name(name), - _password("") + _channelTeam(team), + _ownerGuid(), + _channelName(name), + _channelPassword() { // set special flags if built-in channel if (ChatChannelsEntry const* ch = sChatChannelsStore.LookupEntry(channelId)) // check whether it's a built-in channel { - _announce = false; // no join/leave announces - _ownership = false; // no ownership handout + _announceEnabled = false; // no join/leave announces + _ownershipEnabled = false; // no ownership handout - _flags |= CHANNEL_FLAG_GENERAL; // for all built-in channels + _channelFlags |= CHANNEL_FLAG_GENERAL; // for all built-in channels if (ch->flags & CHANNEL_DBC_FLAG_TRADE) // for trade channel - _flags |= CHANNEL_FLAG_TRADE; + _channelFlags |= CHANNEL_FLAG_TRADE; if (ch->flags & CHANNEL_DBC_FLAG_CITY_ONLY2) // for city only channels - _flags |= CHANNEL_FLAG_CITY; + _channelFlags |= CHANNEL_FLAG_CITY; if (ch->flags & CHANNEL_DBC_FLAG_LFG) // for LFG channel - _flags |= CHANNEL_FLAG_LFG; + _channelFlags |= CHANNEL_FLAG_LFG; else // for all other channels - _flags |= CHANNEL_FLAG_NOT_LFG; + _channelFlags |= CHANNEL_FLAG_NOT_LFG; } else // it's custom channel { - _flags |= CHANNEL_FLAG_CUSTOM; + _channelFlags |= CHANNEL_FLAG_CUSTOM; // If storing custom channels in the db is enabled either load or save the channel if (sWorld->getBoolConfig(CONFIG_PRESERVE_CUSTOM_CHANNELS)) { PreparedStatement *stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHANNEL); stmt->setString(0, name); - stmt->setUInt32(1, _Team); + stmt->setUInt32(1, _channelTeam); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (result) //load { Field* fields = result->Fetch(); - _announce = fields[0].GetBool(); - _ownership = fields[1].GetBool(); - _password = fields[2].GetString(); - const char* db_BannedList = fields[3].GetCString(); + _announceEnabled = fields[0].GetBool(); + _ownershipEnabled = fields[1].GetBool(); + _channelPassword = fields[2].GetString(); + char const* db_BannedList = fields[3].GetCString(); if (db_BannedList) { Tokenizer tokens(db_BannedList, ' '); for (Tokenizer::const_iterator i = tokens.begin(); i != tokens.end(); ++i) { - ObjectGuid banned_guid(uint64(strtoull(*i, NULL, 10))); + ObjectGuid banned_guid(uint64(atoull(*i))); if (banned_guid) { TC_LOG_DEBUG("chat.system", "Channel(%s) loaded bannedStore %s", name.c_str(), banned_guid.ToString().c_str()); - bannedStore.insert(banned_guid); + _bannedStore.insert(banned_guid); } } } @@ -93,45 +93,44 @@ Channel::Channel(std::string const& name, uint32 channelId, uint32 team): { stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHANNEL); stmt->setString(0, name); - stmt->setUInt32(1, _Team); + stmt->setUInt32(1, _channelTeam); CharacterDatabase.Execute(stmt); TC_LOG_DEBUG("chat.system", "Channel(%s) saved in database", name.c_str()); } - _IsSaved = true; + _persistentChannel = true; } } } void Channel::UpdateChannelInDB() const { - if (_IsSaved) + if (_persistentChannel) { std::ostringstream banlist; - BannedContainer::const_iterator iter; - for (iter = bannedStore.begin(); iter != bannedStore.end(); ++iter) + for (BannedContainer::const_iterator iter = _bannedStore.begin(); iter != _bannedStore.end(); ++iter) banlist << iter->GetRawValue() << ' '; std::string banListStr = banlist.str(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL); - stmt->setBool(0, _announce); - stmt->setBool(1, _ownership); - stmt->setString(2, _password); + stmt->setBool(0, _announceEnabled); + stmt->setBool(1, _ownershipEnabled); + stmt->setString(2, _channelPassword); stmt->setString(3, banListStr); - stmt->setString(4, _name); - stmt->setUInt32(5, _Team); + stmt->setString(4, _channelName); + stmt->setUInt32(5, _channelTeam); CharacterDatabase.Execute(stmt); - TC_LOG_DEBUG("chat.system", "Channel(%s) updated in database", _name.c_str()); + TC_LOG_DEBUG("chat.system", "Channel(%s) updated in database", _channelName.c_str()); } } void Channel::UpdateChannelUseageInDB() const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL_USAGE); - stmt->setString(0, _name); - stmt->setUInt32(1, _Team); + stmt->setString(0, _channelName); + stmt->setUInt32(1, _channelTeam); CharacterDatabase.Execute(stmt); } @@ -170,7 +169,7 @@ void Channel::JoinChannel(Player* player, std::string const& pass) return; } - if (!_password.empty() && pass != _password) + if (!_channelPassword.empty() && pass != _channelPassword) { WorldPacket data; MakeWrongPassword(&data); @@ -191,17 +190,15 @@ void Channel::JoinChannel(Player* player, std::string const& pass) player->JoinedChannel(this); - if (_announce && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL)) + if (_announceEnabled && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL)) { WorldPacket data; MakeJoined(&data, guid); SendToAll(&data); } - PlayerInfo pinfo; - pinfo.player = guid; + PlayerInfo& pinfo = _playersStore[guid]; pinfo.flags = MEMBER_FLAG_NONE; - playersStore[guid] = pinfo; WorldPacket data; MakeYouJoined(&data); @@ -213,14 +210,13 @@ void Channel::JoinChannel(Player* player, std::string const& pass) if (!IsConstant()) { // Update last_used timestamp in db - if (!playersStore.empty()) - UpdateChannelUseageInDB(); + UpdateChannelUseageInDB(); // If the channel has no owner yet and ownership is allowed, set the new owner. - if (!_ownerGUID && _ownership) + if (!_ownerGuid && _ownershipEnabled) { - SetOwner(guid, playersStore.size() > 1); - playersStore[guid].SetModerator(true); + SetOwner(guid, _playersStore.size() > 1); + pinfo.SetModerator(true); } } } @@ -248,11 +244,11 @@ void Channel::LeaveChannel(Player* player, bool send) data.clear(); } - bool changeowner = playersStore[guid].IsOwner(); - - playersStore.erase(guid); + PlayerInfo& info = _playersStore.at(guid); + bool changeowner = info.IsOwner(); + _playersStore.erase(guid); - if (_announce && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL)) + if (_announceEnabled && !player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL)) { WorldPacket data; MakeLeft(&data, guid); @@ -266,11 +262,12 @@ void Channel::LeaveChannel(Player* player, bool send) // Update last_used timestamp in db UpdateChannelUseageInDB(); - // If the channel owner left and there are still playersStore inside, pick a new owner - if (changeowner && _ownership && !playersStore.empty()) + // If the channel owner left and there are still players inside, pick a new owner + if (changeowner && _ownershipEnabled && !_playersStore.empty()) { - ObjectGuid newowner = playersStore.begin()->second.player; - playersStore[newowner].SetModerator(true); + auto itr = _playersStore.begin(); + ObjectGuid newowner = itr->first; + itr->second.SetModerator(true); SetOwner(newowner); } } @@ -288,7 +285,8 @@ void Channel::KickOrBan(Player const* player, std::string const& badname, bool b return; } - if (!playersStore[good].IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) + PlayerInfo& info = _playersStore.at(good); + if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) { WorldPacket data; MakeNotModerator(&data); @@ -306,9 +304,9 @@ void Channel::KickOrBan(Player const* player, std::string const& badname, bool b return; } - bool changeowner = _ownerGUID == victim; + bool changeowner = _ownerGuid == victim; - if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR) && changeowner && good != _ownerGUID) + if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR) && changeowner && good != _ownerGuid) { WorldPacket data; MakeNotOwner(&data); @@ -318,7 +316,7 @@ void Channel::KickOrBan(Player const* player, std::string const& badname, bool b if (ban && !IsBanned(victim)) { - bannedStore.insert(victim); + _bannedStore.insert(victim); UpdateChannelInDB(); if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_SILENTLY_JOIN_CHANNEL)) @@ -335,13 +333,13 @@ void Channel::KickOrBan(Player const* player, std::string const& badname, bool b SendToAll(&data); } - playersStore.erase(victim); + _playersStore.erase(victim); bad->LeftChannel(this); - if (changeowner && _ownership && !playersStore.empty()) + if (changeowner && _ownershipEnabled && !_playersStore.empty()) { ObjectGuid newowner = good; - playersStore[newowner].SetModerator(true); + info.SetModerator(true); SetOwner(newowner); } } @@ -358,7 +356,8 @@ void Channel::UnBan(Player const* player, std::string const& badname) return; } - if (!playersStore[good].IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) + PlayerInfo& info = _playersStore.at(good); + if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) { WorldPacket data; MakeNotModerator(&data); @@ -377,7 +376,7 @@ void Channel::UnBan(Player const* player, std::string const& badname) return; } - bannedStore.erase(victim); + _bannedStore.erase(victim); WorldPacket data; MakePlayerUnbanned(&data, victim, good); @@ -399,7 +398,8 @@ void Channel::Password(Player const* player, std::string const& pass) return; } - if (!playersStore[guid].IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) + PlayerInfo& info = _playersStore.at(guid); + if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) { WorldPacket data; MakeNotModerator(&data); @@ -407,7 +407,7 @@ void Channel::Password(Player const* player, std::string const& pass) return; } - _password = pass; + _channelPassword = pass; WorldPacket data; MakePasswordChanged(&data, guid); @@ -428,7 +428,8 @@ void Channel::SetMode(Player const* player, std::string const& p2n, bool mod, bo return; } - if (!playersStore[guid].IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) + PlayerInfo& info = _playersStore.at(guid); + if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) { WorldPacket data; MakeNotModerator(&data); @@ -436,7 +437,7 @@ void Channel::SetMode(Player const* player, std::string const& p2n, bool mod, bo return; } - if (guid == _ownerGUID && std::string(p2n) == player->GetName() && mod) + if (guid == _ownerGuid && std::string(p2n) == player->GetName() && mod) return; Player* newp = ObjectAccessor::FindConnectedPlayerByName(p2n); @@ -453,7 +454,7 @@ void Channel::SetMode(Player const* player, std::string const& p2n, bool mod, bo return; } - if (_ownerGUID == victim && _ownerGUID != guid) + if (_ownerGuid == victim && _ownerGuid != guid) { WorldPacket data; MakeNotOwner(&data); @@ -479,7 +480,7 @@ void Channel::SetOwner(Player const* player, std::string const& newname) return; } - if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR) && guid != _ownerGUID) + if (!player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR) && guid != _ownerGuid) { WorldPacket data; MakeNotOwner(&data); @@ -501,7 +502,8 @@ void Channel::SetOwner(Player const* player, std::string const& newname) return; } - playersStore[victim].SetModerator(true); + PlayerInfo& info = _playersStore.at(victim); + info.SetModerator(true); SetOwner(victim); } @@ -515,7 +517,7 @@ void Channel::SendWhoOwner(ObjectGuid guid) SendToOne(&data, guid); } -void Channel::List(Player const* player) +void Channel::List(Player const* player) const { ObjectGuid guid = player->GetGUID(); @@ -530,7 +532,7 @@ void Channel::List(Player const* player) TC_LOG_DEBUG("chat.system", "SMSG_CHANNEL_LIST %s Channel: %s", player->GetSession()->GetPlayerInfo().c_str(), GetName().c_str()); - WorldPacket data(SMSG_CHANNEL_LIST, 1+(GetName().size()+1)+1+4+playersStore.size()*(8+1)); + WorldPacket data(SMSG_CHANNEL_LIST, 1+(GetName().size()+1)+1+4+_playersStore.size()*(8+1)); data << uint8(1); // channel type? data << GetName(); // channel name data << uint8(GetFlags()); // channel flags? @@ -541,7 +543,7 @@ void Channel::List(Player const* player) uint32 gmLevelInWhoList = sWorld->getIntConfig(CONFIG_GM_LEVEL_IN_WHO_LIST); uint32 count = 0; - for (PlayerContainer::const_iterator i = playersStore.begin(); i != playersStore.end(); ++i) + for (PlayerContainer::const_iterator i = _playersStore.begin(); i != _playersStore.end(); ++i) { Player* member = ObjectAccessor::FindConnectedPlayer(i->first); @@ -575,7 +577,8 @@ void Channel::Announce(Player const* player) return; } - if (!playersStore[guid].IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) + PlayerInfo& info = _playersStore.at(guid); + if (!info.IsModerator() && !player->GetSession()->HasPermission(rbac::RBAC_PERM_CHANGE_CHANNEL_NOT_MODERATOR)) { WorldPacket data; MakeNotModerator(&data); @@ -583,10 +586,10 @@ void Channel::Announce(Player const* player) return; } - _announce = !_announce; + _announceEnabled = !_announceEnabled; WorldPacket data; - if (_announce) + if (_announceEnabled) MakeAnnouncementsOn(&data, guid); else MakeAnnouncementsOff(&data, guid); @@ -595,7 +598,7 @@ void Channel::Announce(Player const* player) UpdateChannelInDB(); } -void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) +void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) const { if (what.empty()) return; @@ -612,7 +615,8 @@ void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) return; } - if (playersStore[guid].IsMuted()) + PlayerInfo const& info = _playersStore.at(guid); + if (info.IsMuted()) { WorldPacket data; MakeMuted(&data); @@ -622,11 +626,11 @@ void Channel::Say(ObjectGuid guid, std::string const& what, uint32 lang) WorldPacket data; if (Player* player = ObjectAccessor::FindConnectedPlayer(guid)) - ChatHandler::BuildChatPacket(data, CHAT_MSG_CHANNEL, Language(lang), player, player, what, 0, _name); + ChatHandler::BuildChatPacket(data, CHAT_MSG_CHANNEL, Language(lang), player, player, what, 0, _channelName); else - ChatHandler::BuildChatPacket(data, CHAT_MSG_CHANNEL, Language(lang), guid, guid, what, 0, "", "", 0, false, _name); + ChatHandler::BuildChatPacket(data, CHAT_MSG_CHANNEL, Language(lang), guid, guid, what, 0, "", "", 0, false, _channelName); - SendToAll(&data, !playersStore[guid].IsModerator() ? guid : ObjectGuid::Empty); + SendToAll(&data, !info.IsModerator() ? guid : ObjectGuid::Empty); } void Channel::Invite(Player const* player, std::string const& newname) @@ -691,28 +695,31 @@ void Channel::Invite(Player const* player, std::string const& newname) void Channel::SetOwner(ObjectGuid guid, bool exclaim) { - if (_ownerGUID) + if (_ownerGuid) { - // [] will re-add player after it possible removed - PlayerContainer::iterator p_itr = playersStore.find(_ownerGUID); - if (p_itr != playersStore.end()) - p_itr->second.SetOwner(false); + auto itr = _playersStore.find(_ownerGuid); + if (itr != _playersStore.end()) + itr->second.SetOwner(false); } - _ownerGUID = guid; - if (_ownerGUID) + _ownerGuid = guid; + if (_ownerGuid) { - uint8 oldFlag = GetPlayerFlags(_ownerGUID); - playersStore[_ownerGUID].SetModerator(true); - playersStore[_ownerGUID].SetOwner(true); + uint8 oldFlag = GetPlayerFlags(_ownerGuid); + auto itr = _playersStore.find(_ownerGuid); + if (itr == _playersStore.end()) + return; + + itr->second.SetModerator(true); + itr->second.SetOwner(true); WorldPacket data; - MakeModeChange(&data, _ownerGUID, oldFlag); + MakeModeChange(&data, _ownerGuid, oldFlag); SendToAll(&data); if (exclaim) { - MakeOwnerChanged(&data, _ownerGUID); + MakeOwnerChanged(&data, _ownerGuid); SendToAll(&data); } @@ -720,58 +727,58 @@ void Channel::SetOwner(ObjectGuid guid, bool exclaim) } } -void Channel::SendToAll(WorldPacket* data, ObjectGuid guid) +void Channel::SendToAll(WorldPacket* data, ObjectGuid guid) const { - for (PlayerContainer::const_iterator i = playersStore.begin(); i != playersStore.end(); ++i) + for (PlayerContainer::const_iterator i = _playersStore.begin(); i != _playersStore.end(); ++i) if (Player* player = ObjectAccessor::FindConnectedPlayer(i->first)) if (!guid || !player->GetSocial()->HasIgnore(guid.GetCounter())) player->GetSession()->SendPacket(data); } -void Channel::SendToAllButOne(WorldPacket* data, ObjectGuid who) +void Channel::SendToAllButOne(WorldPacket* data, ObjectGuid who) const { - for (PlayerContainer::const_iterator i = playersStore.begin(); i != playersStore.end(); ++i) + for (PlayerContainer::const_iterator i = _playersStore.begin(); i != _playersStore.end(); ++i) if (i->first != who) if (Player* player = ObjectAccessor::FindConnectedPlayer(i->first)) player->GetSession()->SendPacket(data); } -void Channel::SendToOne(WorldPacket* data, ObjectGuid who) +void Channel::SendToOne(WorldPacket* data, ObjectGuid who) const { if (Player* player = ObjectAccessor::FindConnectedPlayer(who)) player->GetSession()->SendPacket(data); } -void Channel::Voice(ObjectGuid /*guid1*/, ObjectGuid /*guid2*/) +void Channel::Voice(ObjectGuid /*guid1*/, ObjectGuid /*guid2*/) const { } -void Channel::DeVoice(ObjectGuid /*guid1*/, ObjectGuid /*guid2*/) +void Channel::DeVoice(ObjectGuid /*guid1*/, ObjectGuid /*guid2*/) const { } -void Channel::MakeNotifyPacket(WorldPacket* data, uint8 notify_type) +void Channel::MakeNotifyPacket(WorldPacket* data, uint8 notify_type) const { - data->Initialize(SMSG_CHANNEL_NOTIFY, 1 + _name.size()); + data->Initialize(SMSG_CHANNEL_NOTIFY, 1 + _channelName.size()); *data << uint8(notify_type); - *data << _name; + *data << _channelName; } -void Channel::MakeJoined(WorldPacket* data, ObjectGuid guid) +void Channel::MakeJoined(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_JOINED_NOTICE); *data << uint64(guid); } -void Channel::MakeLeft(WorldPacket* data, ObjectGuid guid) +void Channel::MakeLeft(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_LEFT_NOTICE); *data << uint64(guid); } -void Channel::MakeYouJoined(WorldPacket* data) +void Channel::MakeYouJoined(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_YOU_JOINED_NOTICE); *data << uint8(GetFlags()); @@ -779,63 +786,66 @@ void Channel::MakeYouJoined(WorldPacket* data) *data << uint32(0); } -void Channel::MakeYouLeft(WorldPacket* data) +void Channel::MakeYouLeft(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_YOU_LEFT_NOTICE); *data << uint32(GetChannelId()); *data << uint8(IsConstant()); } -void Channel::MakeWrongPassword(WorldPacket* data) +void Channel::MakeWrongPassword(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_WRONG_PASSWORD_NOTICE); } -void Channel::MakeNotMember(WorldPacket* data) +void Channel::MakeNotMember(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_MEMBER_NOTICE); } -void Channel::MakeNotModerator(WorldPacket* data) +void Channel::MakeNotModerator(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_MODERATOR_NOTICE); } -void Channel::MakePasswordChanged(WorldPacket* data, ObjectGuid guid) +void Channel::MakePasswordChanged(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_PASSWORD_CHANGED_NOTICE); *data << uint64(guid); } -void Channel::MakeOwnerChanged(WorldPacket* data, ObjectGuid guid) +void Channel::MakeOwnerChanged(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_OWNER_CHANGED_NOTICE); *data << uint64(guid); } -void Channel::MakePlayerNotFound(WorldPacket* data, std::string const& name) +void Channel::MakePlayerNotFound(WorldPacket* data, std::string const& name) const { MakeNotifyPacket(data, CHAT_PLAYER_NOT_FOUND_NOTICE); *data << name; } -void Channel::MakeNotOwner(WorldPacket* data) +void Channel::MakeNotOwner(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_OWNER_NOTICE); } -void Channel::MakeChannelOwner(WorldPacket* data) +void Channel::MakeChannelOwner(WorldPacket* data) const { - std::string name = ""; + std::string name; - if (!sObjectMgr->GetPlayerNameByGUID(_ownerGUID, name) || name.empty()) + CharacterInfo const* cInfo = sWorld->GetCharacterInfo(_ownerGuid); + if (!cInfo || cInfo->Name.empty()) name = "PLAYER_NOT_FOUND"; + else + name = cInfo->Name; MakeNotifyPacket(data, CHAT_CHANNEL_OWNER_NOTICE); - *data << ((IsConstant() || !_ownerGUID) ? "Nobody" : name); + *data << ((IsConstant() || !_ownerGuid) ? "Nobody" : name); } -void Channel::MakeModeChange(WorldPacket* data, ObjectGuid guid, uint8 oldflags) +void Channel::MakeModeChange(WorldPacket* data, ObjectGuid guid, uint8 oldflags) const { MakeNotifyPacket(data, CHAT_MODE_CHANGE_NOTICE); *data << uint64(guid); @@ -843,127 +853,127 @@ void Channel::MakeModeChange(WorldPacket* data, ObjectGuid guid, uint8 oldflags) *data << uint8(GetPlayerFlags(guid)); } -void Channel::MakeAnnouncementsOn(WorldPacket* data, ObjectGuid guid) +void Channel::MakeAnnouncementsOn(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_ANNOUNCEMENTS_ON_NOTICE); *data << uint64(guid); } -void Channel::MakeAnnouncementsOff(WorldPacket* data, ObjectGuid guid) +void Channel::MakeAnnouncementsOff(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_ANNOUNCEMENTS_OFF_NOTICE); *data << uint64(guid); } -void Channel::MakeMuted(WorldPacket* data) +void Channel::MakeMuted(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_MUTED_NOTICE); } -void Channel::MakePlayerKicked(WorldPacket* data, ObjectGuid bad, ObjectGuid good) +void Channel::MakePlayerKicked(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const { MakeNotifyPacket(data, CHAT_PLAYER_KICKED_NOTICE); *data << uint64(bad); *data << uint64(good); } -void Channel::MakeBanned(WorldPacket* data) +void Channel::MakeBanned(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_BANNED_NOTICE); } -void Channel::MakePlayerBanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) +void Channel::MakePlayerBanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const { MakeNotifyPacket(data, CHAT_PLAYER_BANNED_NOTICE); *data << uint64(bad); *data << uint64(good); } -void Channel::MakePlayerUnbanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) +void Channel::MakePlayerUnbanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const { MakeNotifyPacket(data, CHAT_PLAYER_UNBANNED_NOTICE); *data << uint64(bad); *data << uint64(good); } -void Channel::MakePlayerNotBanned(WorldPacket* data, const std::string &name) +void Channel::MakePlayerNotBanned(WorldPacket* data, const std::string &name) const { MakeNotifyPacket(data, CHAT_PLAYER_NOT_BANNED_NOTICE); *data << name; } -void Channel::MakePlayerAlreadyMember(WorldPacket* data, ObjectGuid guid) +void Channel::MakePlayerAlreadyMember(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_PLAYER_ALREADY_MEMBER_NOTICE); *data << uint64(guid); } -void Channel::MakeInvite(WorldPacket* data, ObjectGuid guid) +void Channel::MakeInvite(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_INVITE_NOTICE); *data << uint64(guid); } -void Channel::MakeInviteWrongFaction(WorldPacket* data) +void Channel::MakeInviteWrongFaction(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_INVITE_WRONG_FACTION_NOTICE); } -void Channel::MakeWrongFaction(WorldPacket* data) +void Channel::MakeWrongFaction(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_WRONG_FACTION_NOTICE); } -void Channel::MakeInvalidName(WorldPacket* data) +void Channel::MakeInvalidName(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_INVALID_NAME_NOTICE); } -void Channel::MakeNotModerated(WorldPacket* data) +void Channel::MakeNotModerated(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_MODERATED_NOTICE); } -void Channel::MakePlayerInvited(WorldPacket* data, const std::string& name) +void Channel::MakePlayerInvited(WorldPacket* data, std::string const& name) const { MakeNotifyPacket(data, CHAT_PLAYER_INVITED_NOTICE); *data << name; } -void Channel::MakePlayerInviteBanned(WorldPacket* data, const std::string& name) +void Channel::MakePlayerInviteBanned(WorldPacket* data, std::string const& name) const { MakeNotifyPacket(data, CHAT_PLAYER_INVITE_BANNED_NOTICE); *data << name; } -void Channel::MakeThrottled(WorldPacket* data) +void Channel::MakeThrottled(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_THROTTLED_NOTICE); } -void Channel::MakeNotInArea(WorldPacket* data) +void Channel::MakeNotInArea(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_IN_AREA_NOTICE); } -void Channel::MakeNotInLfg(WorldPacket* data) +void Channel::MakeNotInLfg(WorldPacket* data) const { MakeNotifyPacket(data, CHAT_NOT_IN_LFG_NOTICE); } -void Channel::MakeVoiceOn(WorldPacket* data, ObjectGuid guid) +void Channel::MakeVoiceOn(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_VOICE_ON_NOTICE); *data << uint64(guid); } -void Channel::MakeVoiceOff(WorldPacket* data, ObjectGuid guid) +void Channel::MakeVoiceOff(WorldPacket* data, ObjectGuid guid) const { MakeNotifyPacket(data, CHAT_VOICE_OFF_NOTICE); *data << uint64(guid); } -void Channel::JoinNotify(ObjectGuid guid) +void Channel::JoinNotify(ObjectGuid guid) const { WorldPacket data(IsConstant() ? SMSG_USERLIST_ADD : SMSG_USERLIST_UPDATE, 8 + 1 + 1 + 4 + GetName().size()); data << uint64(guid); @@ -978,7 +988,7 @@ void Channel::JoinNotify(ObjectGuid guid) SendToAll(&data); } -void Channel::LeaveNotify(ObjectGuid guid) +void Channel::LeaveNotify(ObjectGuid guid) const { WorldPacket data(SMSG_USERLIST_REMOVE, 8 + 1 + 4 + GetName().size()); data << uint64(guid); diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index 26bc6989d07..23f9e5ae28f 100644 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -19,10 +19,6 @@ #ifndef _CHANNEL_H #define _CHANNEL_H -#include <list> -#include <map> -#include <string> - #include "Common.h" #include "WorldSession.h" @@ -53,10 +49,10 @@ enum ChatNotify CHAT_MODERATION_OFF_NOTICE = 0x10, //+ "[%s] Channel moderation disabled by %s."; CHAT_MUTED_NOTICE = 0x11, //+ "[%s] You do not have permission to speak."; CHAT_PLAYER_KICKED_NOTICE = 0x12, //? "[%s] Player %s kicked by %s."; - CHAT_BANNED_NOTICE = 0x13, //+ "[%s] You are bannedStore from that channel."; - CHAT_PLAYER_BANNED_NOTICE = 0x14, //? "[%s] Player %s bannedStore by %s."; + CHAT_BANNED_NOTICE = 0x13, //+ "[%s] You are banned from that channel."; + CHAT_PLAYER_BANNED_NOTICE = 0x14, //? "[%s] Player %s banned by %s."; CHAT_PLAYER_UNBANNED_NOTICE = 0x15, //? "[%s] Player %s unbanned by %s."; - CHAT_PLAYER_NOT_BANNED_NOTICE = 0x16, //+ "[%s] Player %s is not bannedStore."; + CHAT_PLAYER_NOT_BANNED_NOTICE = 0x16, //+ "[%s] Player %s is not banned."; CHAT_PLAYER_ALREADY_MEMBER_NOTICE = 0x17, //+ "[%s] Player %s is already on the channel."; CHAT_INVITE_NOTICE = 0x18, //+ "%2$s has invited you to join the channel '%1$s'."; CHAT_INVITE_WRONG_FACTION_NOTICE = 0x19, //+ "Target is in the wrong alliance for %s."; @@ -64,7 +60,7 @@ enum ChatNotify CHAT_INVALID_NAME_NOTICE = 0x1B, //+ "Invalid channel name"; CHAT_NOT_MODERATED_NOTICE = 0x1C, //+ "%s is not moderated"; CHAT_PLAYER_INVITED_NOTICE = 0x1D, //+ "[%s] You invited %s to join the channel"; - CHAT_PLAYER_INVITE_BANNED_NOTICE = 0x1E, //+ "[%s] %s has been bannedStore."; + CHAT_PLAYER_INVITE_BANNED_NOTICE = 0x1E, //+ "[%s] %s has been banned."; CHAT_THROTTLED_NOTICE = 0x1F, //+ "[%s] The number of messages that can be sent to this channel is limited, please wait to send another message."; CHAT_NOT_IN_AREA_NOTICE = 0x20, //+ "[%s] You are not in the correct area for this channel."; -- The user is trying to send a chat to a zone specific channel, and they're not physically in that zone. CHAT_NOT_IN_LFG_NOTICE = 0x21, //+ "[%s] You must be queued in looking for group before joining this channel."; -- The user must be in the looking for group system to join LFG chat channels. @@ -85,7 +81,7 @@ enum ChannelFlags CHANNEL_FLAG_VOICE = 0x80 // General 0x18 = 0x10 | 0x08 // Trade 0x3C = 0x20 | 0x10 | 0x08 | 0x04 - // LocalDefence 0x18 = 0x10 | 0x08 + // LocalDefense 0x18 = 0x10 | 0x08 // GuildRecruitment 0x38 = 0x20 | 0x10 | 0x08 // LookingForGroup 0x50 = 0x40 | 0x10 }; @@ -118,27 +114,29 @@ enum ChannelMemberFlags // 0x80 }; -class Channel +class TC_GAME_API Channel { struct PlayerInfo { - ObjectGuid player; uint8 flags; bool HasFlag(uint8 flag) const { return (flags & flag) != 0; } void SetFlag(uint8 flag) { flags |= flag; } + bool IsOwner() const { return (flags & MEMBER_FLAG_OWNER) != 0; } void SetOwner(bool state) { if (state) flags |= MEMBER_FLAG_OWNER; else flags &= ~MEMBER_FLAG_OWNER; } + bool IsModerator() const { return (flags & MEMBER_FLAG_MODERATOR) != 0; } void SetModerator(bool state) { if (state) flags |= MEMBER_FLAG_MODERATOR; else flags &= ~MEMBER_FLAG_MODERATOR; } + bool IsMuted() const { return (flags & MEMBER_FLAG_MUTED) != 0; } void SetMuted(bool state) { @@ -148,106 +146,121 @@ class Channel }; public: - Channel(std::string const& name, uint32 channel_id, uint32 Team = 0); - std::string const& GetName() const { return _name; } + Channel(std::string const& name, uint32 channel_id, uint32 team = 0); + + std::string const& GetName() const { return _channelName; } + uint32 GetChannelId() const { return _channelId; } bool IsConstant() const { return _channelId != 0; } - bool IsAnnounce() const { return _announce; } bool IsLFG() const { return (GetFlags() & CHANNEL_FLAG_LFG) != 0; } - std::string const& GetPassword() const { return _password; } - void SetPassword(std::string const& npassword) { _password = npassword; } - void SetAnnounce(bool nannounce) { _announce = nannounce; } - uint32 GetNumPlayers() const { return playersStore.size(); } - uint8 GetFlags() const { return _flags; } - bool HasFlag(uint8 flag) const { return (_flags & flag) != 0; } + + bool IsAnnounce() const { return _announceEnabled; } + void SetAnnounce(bool nannounce) { _announceEnabled = nannounce; } + + std::string const& GetPassword() const { return _channelPassword; } + void SetPassword(std::string const& npassword) { _channelPassword = npassword; } + + uint32 GetNumPlayers() const { return _playersStore.size(); } + + uint8 GetFlags() const { return _channelFlags; } + bool HasFlag(uint8 flag) const { return (_channelFlags & flag) != 0; } void JoinChannel(Player* player, std::string const& pass); void LeaveChannel(Player* player, bool send = true); + void KickOrBan(Player const* player, std::string const& badname, bool ban); void Kick(Player const* player, std::string const& badname) { KickOrBan(player, badname, false); } void Ban(Player const* player, std::string const& badname) { KickOrBan(player, badname, true); } + void UnBan(Player const* player, std::string const& badname); void Password(Player const* player, std::string const& pass); void SetMode(Player const* player, std::string const& p2n, bool mod, bool set); - void SetOwner(ObjectGuid guid, bool exclaim = true); - void SetOwner(Player const* player, std::string const& name); - void SendWhoOwner(ObjectGuid guid); + void SetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, true); } void UnsetModerator(Player const* player, std::string const& newname) { SetMode(player, newname, true, false); } void SetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, true); } void UnsetMute(Player const* player, std::string const& newname) { SetMode(player, newname, false, false); } - void List(Player const* player); + + void SetOwner(ObjectGuid guid, bool exclaim = true); + void SetOwner(Player const* player, std::string const& name); + void SendWhoOwner(ObjectGuid guid); + + void List(Player const* player) const; void Announce(Player const* player); - void Say(ObjectGuid guid, std::string const& what, uint32 lang); + void Say(ObjectGuid guid, std::string const& what, uint32 lang) const; void Invite(Player const* player, std::string const& newp); - void Voice(ObjectGuid guid1, ObjectGuid guid2); - void DeVoice(ObjectGuid guid1, ObjectGuid guid2); - void JoinNotify(ObjectGuid guid); // invisible notify - void LeaveNotify(ObjectGuid guid); // invisible notify - void SetOwnership(bool ownership) { _ownership = ownership; } + void Voice(ObjectGuid guid1, ObjectGuid guid2) const; + void DeVoice(ObjectGuid guid1, ObjectGuid guid2) const; + void JoinNotify(ObjectGuid guid) const; // invisible notify + void LeaveNotify(ObjectGuid guid) const; // invisible notify + void SetOwnership(bool ownership) { _ownershipEnabled = ownership; } static void CleanOldChannelsInDB(); private: // initial packet data (notify type and channel name) - void MakeNotifyPacket(WorldPacket* data, uint8 notify_type); + void MakeNotifyPacket(WorldPacket* data, uint8 notify_type) const; // type specific packet data - void MakeJoined(WorldPacket* data, ObjectGuid guid); //+ 0x00 - void MakeLeft(WorldPacket* data, ObjectGuid guid); //+ 0x01 - void MakeYouJoined(WorldPacket* data); //+ 0x02 - void MakeYouLeft(WorldPacket* data); //+ 0x03 - void MakeWrongPassword(WorldPacket* data); //? 0x04 - void MakeNotMember(WorldPacket* data); //? 0x05 - void MakeNotModerator(WorldPacket* data); //? 0x06 - void MakePasswordChanged(WorldPacket* data, ObjectGuid guid); //+ 0x07 - void MakeOwnerChanged(WorldPacket* data, ObjectGuid guid); //? 0x08 - void MakePlayerNotFound(WorldPacket* data, std::string const& name); //+ 0x09 - void MakeNotOwner(WorldPacket* data); //? 0x0A - void MakeChannelOwner(WorldPacket* data); //? 0x0B - void MakeModeChange(WorldPacket* data, ObjectGuid guid, uint8 oldflags);//+ 0x0C - void MakeAnnouncementsOn(WorldPacket* data, ObjectGuid guid); //+ 0x0D - void MakeAnnouncementsOff(WorldPacket* data, ObjectGuid guid); //+ 0x0E - void MakeMuted(WorldPacket* data); //? 0x11 - void MakePlayerKicked(WorldPacket* data, ObjectGuid bad, ObjectGuid good);//? 0x12 - void MakeBanned(WorldPacket* data); //? 0x13 - void MakePlayerBanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good);//? 0x14 - void MakePlayerUnbanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good);//? 0x15 - void MakePlayerNotBanned(WorldPacket* data, std::string const& name); //? 0x16 - void MakePlayerAlreadyMember(WorldPacket* data, ObjectGuid guid); //+ 0x17 - void MakeInvite(WorldPacket* data, ObjectGuid guid); //? 0x18 - void MakeInviteWrongFaction(WorldPacket* data); //? 0x19 - void MakeWrongFaction(WorldPacket* data); //? 0x1A - void MakeInvalidName(WorldPacket* data); //? 0x1B - void MakeNotModerated(WorldPacket* data); //? 0x1C - void MakePlayerInvited(WorldPacket* data, std::string const& name); //+ 0x1D - void MakePlayerInviteBanned(WorldPacket* data, std::string const& name);//? 0x1E - void MakeThrottled(WorldPacket* data); //? 0x1F - void MakeNotInArea(WorldPacket* data); //? 0x20 - void MakeNotInLfg(WorldPacket* data); //? 0x21 - void MakeVoiceOn(WorldPacket* data, ObjectGuid guid); //+ 0x22 - void MakeVoiceOff(WorldPacket* data, ObjectGuid guid); //+ 0x23 - - void SendToAll(WorldPacket* data, ObjectGuid guid = ObjectGuid::Empty); - void SendToAllButOne(WorldPacket* data, ObjectGuid who); - void SendToOne(WorldPacket* data, ObjectGuid who); - - bool IsOn(ObjectGuid who) const { return playersStore.find(who) != playersStore.end(); } - bool IsBanned(ObjectGuid guid) const { return bannedStore.find(guid) != bannedStore.end(); } + void MakeJoined(WorldPacket* data, ObjectGuid guid) const; //+ 0x00 + void MakeLeft(WorldPacket* data, ObjectGuid guid) const; //+ 0x01 + void MakeYouJoined(WorldPacket* data) const; //+ 0x02 + void MakeYouLeft(WorldPacket* data) const; //+ 0x03 + void MakeWrongPassword(WorldPacket* data) const; //? 0x04 + void MakeNotMember(WorldPacket* data) const; //? 0x05 + void MakeNotModerator(WorldPacket* data) const; //? 0x06 + void MakePasswordChanged(WorldPacket* data, ObjectGuid guid) const; //+ 0x07 + void MakeOwnerChanged(WorldPacket* data, ObjectGuid guid) const; //? 0x08 + void MakePlayerNotFound(WorldPacket* data, std::string const& name) const; //+ 0x09 + void MakeNotOwner(WorldPacket* data) const; //? 0x0A + void MakeChannelOwner(WorldPacket* data) const; //? 0x0B + void MakeModeChange(WorldPacket* data, ObjectGuid guid, uint8 oldflags) const; //+ 0x0C + void MakeAnnouncementsOn(WorldPacket* data, ObjectGuid guid) const; //+ 0x0D + void MakeAnnouncementsOff(WorldPacket* data, ObjectGuid guid) const; //+ 0x0E + void MakeMuted(WorldPacket* data) const; //? 0x11 + void MakePlayerKicked(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const; //? 0x12 + void MakeBanned(WorldPacket* data) const; //? 0x13 + void MakePlayerBanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const; //? 0x14 + void MakePlayerUnbanned(WorldPacket* data, ObjectGuid bad, ObjectGuid good) const; //? 0x15 + void MakePlayerNotBanned(WorldPacket* data, std::string const& name) const; //? 0x16 + void MakePlayerAlreadyMember(WorldPacket* data, ObjectGuid guid) const; //+ 0x17 + void MakeInvite(WorldPacket* data, ObjectGuid guid) const; //? 0x18 + void MakeInviteWrongFaction(WorldPacket* data) const; //? 0x19 + void MakeWrongFaction(WorldPacket* data) const; //? 0x1A + void MakeInvalidName(WorldPacket* data) const; //? 0x1B + void MakeNotModerated(WorldPacket* data) const; //? 0x1C + void MakePlayerInvited(WorldPacket* data, std::string const& name) const; //+ 0x1D + void MakePlayerInviteBanned(WorldPacket* data, std::string const& name) const; //? 0x1E + void MakeThrottled(WorldPacket* data) const; //? 0x1F + void MakeNotInArea(WorldPacket* data) const; //? 0x20 + void MakeNotInLfg(WorldPacket* data) const; //? 0x21 + void MakeVoiceOn(WorldPacket* data, ObjectGuid guid) const; //+ 0x22 + void MakeVoiceOff(WorldPacket* data, ObjectGuid guid) const; //+ 0x23 + + void SendToAll(WorldPacket* data, ObjectGuid guid = ObjectGuid::Empty) const; + void SendToAllButOne(WorldPacket* data, ObjectGuid who) const; + void SendToOne(WorldPacket* data, ObjectGuid who) const; + + bool IsOn(ObjectGuid who) const { return _playersStore.count(who) != 0; } + bool IsBanned(ObjectGuid guid) const { return _bannedStore.count(guid) != 0; } void UpdateChannelInDB() const; void UpdateChannelUseageInDB() const; uint8 GetPlayerFlags(ObjectGuid guid) const { - PlayerContainer::const_iterator itr = playersStore.find(guid); - return itr != playersStore.end() ? itr->second.flags : 0; + PlayerContainer::const_iterator itr = _playersStore.find(guid); + return itr != _playersStore.end() ? itr->second.flags : 0; } void SetModerator(ObjectGuid guid, bool set) { - if (playersStore[guid].IsModerator() != set) + if (!IsOn(guid)) + return; + + PlayerInfo& playerInfo = _playersStore.at(guid); + if (playerInfo.IsModerator() != set) { uint8 oldFlag = GetPlayerFlags(guid); - playersStore[guid].SetModerator(set); + playerInfo.SetModerator(set); WorldPacket data; MakeModeChange(&data, guid, oldFlag); @@ -257,10 +270,14 @@ class Channel void SetMute(ObjectGuid guid, bool set) { - if (playersStore[guid].IsMuted() != set) + if (!IsOn(guid)) + return; + + PlayerInfo& playerInfo = _playersStore.at(guid); + if (playerInfo.IsMuted() != set) { uint8 oldFlag = GetPlayerFlags(guid); - playersStore[guid].SetMuted(set); + playerInfo.SetMuted(set); WorldPacket data; MakeModeChange(&data, guid, oldFlag); @@ -269,19 +286,20 @@ class Channel } typedef std::map<ObjectGuid, PlayerInfo> PlayerContainer; - typedef GuidSet BannedContainer; + typedef GuidUnorderedSet BannedContainer; + + bool _announceEnabled; //< Whether we should broadcast a packet whenever a player joins/exits the channel + bool _ownershipEnabled; //< Whether the channel has to maintain an owner + bool _persistentChannel; //< Whether the channel is saved to DB - bool _announce; - bool _ownership; - bool _IsSaved; - uint8 _flags; + uint8 _channelFlags; uint32 _channelId; - uint32 _Team; - ObjectGuid _ownerGUID; - std::string _name; - std::string _password; - PlayerContainer playersStore; - BannedContainer bannedStore; + uint32 _channelTeam; + ObjectGuid _ownerGuid; + std::string _channelName; + std::string _channelPassword; + PlayerContainer _playersStore; + BannedContainer _bannedStore; }; #endif diff --git a/src/server/game/Chat/Channels/ChannelMgr.cpp b/src/server/game/Chat/Channels/ChannelMgr.cpp index 3e9a633729a..043d4bdc2bc 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.cpp +++ b/src/server/game/Chat/Channels/ChannelMgr.cpp @@ -39,14 +39,14 @@ ChannelMgr* ChannelMgr::forTeam(uint32 team) if (team == HORDE) return &hordeChannelMgr; - return NULL; + return nullptr; } Channel* ChannelMgr::GetJoinChannel(std::string const& name, uint32 channelId) { std::wstring wname; if (!Utf8toWStr(name, wname)) - return NULL; + return nullptr; wstrToLower(wname); @@ -66,7 +66,7 @@ Channel* ChannelMgr::GetChannel(std::string const& name, Player* player, bool pk { std::wstring wname; if (!Utf8toWStr(name, wname)) - return NULL; + return nullptr; wstrToLower(wname); @@ -81,7 +81,7 @@ Channel* ChannelMgr::GetChannel(std::string const& name, Player* player, bool pk player->GetSession()->SendPacket(&data); } - return NULL; + return nullptr; } return i->second; diff --git a/src/server/game/Chat/Channels/ChannelMgr.h b/src/server/game/Chat/Channels/ChannelMgr.h index 2cd4edc4fb1..abe45690997 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.h +++ b/src/server/game/Chat/Channels/ChannelMgr.h @@ -28,7 +28,7 @@ #define MAX_CHANNEL_PASS_STR 31 -class ChannelMgr +class TC_GAME_API ChannelMgr { typedef std::map<std::wstring, Channel*> ChannelMap; diff --git a/src/server/game/Chat/Chat.cpp b/src/server/game/Chat/Chat.cpp index 8fe0810f3b9..27fa7ffb409 100644 --- a/src/server/game/Chat/Chat.cpp +++ b/src/server/game/Chat/Chat.cpp @@ -32,18 +32,19 @@ #include "ScriptMgr.h" #include "ChatLink.h" -bool ChatHandler::load_command_table = true; +// Lazy loading of the command table cache from commands and the +// ScriptMgr should be thread safe since the player commands, +// cli commands and ScriptMgr updates are all dispatched one after +// one inside the world update loop. +static Optional<std::vector<ChatCommand>> commandTableCache; std::vector<ChatCommand> const& ChatHandler::getCommandTable() { - static std::vector<ChatCommand> commandTableCache; - - if (LoadCommandTable()) + if (!commandTableCache) { - SetLoadCommandTable(false); - - std::vector<ChatCommand> cmds = sScriptMgr->GetChatCommands(); - commandTableCache.swap(cmds); + // We need to initialize this at top since SetDataForCommandInTable + // calls getCommandTable() recursively. + commandTableCache = sScriptMgr->GetChatCommands(); PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_COMMANDS); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -54,13 +55,18 @@ std::vector<ChatCommand> const& ChatHandler::getCommandTable() Field* fields = result->Fetch(); std::string name = fields[0].GetString(); - SetDataForCommandInTable(commandTableCache, name.c_str(), fields[1].GetUInt16(), fields[2].GetString(), name); + SetDataForCommandInTable(*commandTableCache, name.c_str(), fields[1].GetUInt16(), fields[2].GetString(), name); } while (result->NextRow()); } } - return commandTableCache; + return *commandTableCache; +} + +void ChatHandler::invalidateCommandTable() +{ + commandTableCache.reset(); } char const* ChatHandler::GetTrinityString(uint32 entry) const @@ -75,7 +81,7 @@ bool ChatHandler::isAvailable(ChatCommand const& cmd) const bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) { - WorldSession* target_session = NULL; + WorldSession* target_session = nullptr; uint32 target_account = 0; if (target) @@ -108,9 +114,9 @@ bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_ac if (target) target_sec = target->GetSecurity(); else if (target_account) - target_sec = AccountMgr::GetSecurity(target_account, realmID); + target_sec = AccountMgr::GetSecurity(target_account, realm.Id.Realm); else - return true; // caller must report error for (target == NULL && target_account == 0) + return true; // caller must report error for (target == nullptr && target_account == 0) AccountTypes target_ac_sec = AccountTypes(target_sec); if (m_session->GetSecurity() < target_ac_sec || (strong && m_session->GetSecurity() <= target_ac_sec)) @@ -123,7 +129,7 @@ bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_ac return false; } -bool ChatHandler::hasStringAbbr(const char* name, const char* part) +bool ChatHandler::hasStringAbbr(char const* name, char const* part) { // non "" command if (*name) @@ -160,7 +166,7 @@ void ChatHandler::SendSysMessage(const char *str, bool escapeCharacters) { size_t startPos = 0; std::ostringstream o; - while (const char* charPos = strchr(str + startPos, '|')) + while (char const* charPos = strchr(str + startPos, '|')) { o.write(str + startPos, charPos - str - startPos); o << "||"; @@ -178,7 +184,7 @@ void ChatHandler::SendSysMessage(const char *str, bool escapeCharacters) while (char* line = LineFromMessage(pos)) { - BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); m_session->SendPacket(&data); } @@ -196,7 +202,7 @@ void ChatHandler::SendGlobalSysMessage(const char *str) while (char* line = LineFromMessage(pos)) { - BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); sWorld->SendGlobalMessage(&data); } @@ -214,7 +220,7 @@ void ChatHandler::SendGlobalGMSysMessage(const char *str) while (char* line = LineFromMessage(pos)) { - BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); sWorld->SendGlobalGMMessage(&data); } @@ -226,7 +232,7 @@ void ChatHandler::SendSysMessage(uint32 entry) SendSysMessage(GetTrinityString(entry)); } -bool ChatHandler::ExecuteCommandInTable(std::vector<ChatCommand> const& table, const char* text, std::string const& fullcmd) +bool ChatHandler::ExecuteCommandInTable(std::vector<ChatCommand> const& table, char const* text, std::string const& fullcmd) { char const* oldtext = text; std::string cmd = ""; @@ -360,7 +366,7 @@ bool ChatHandler::SetDataForCommandInTable(std::vector<ChatCommand>& table, char // expected subcommand by full name DB content else if (*text) { - TC_LOG_ERROR("sql.sql", "Table `command` have unexpected subcommand '%s' in command '%s', skip.", text, fullcommand.c_str()); + TC_LOG_ERROR("sql.sql", "Table `command` contains an unexpected subcommand '%s' in command '%s', skipped.", text, fullcommand.c_str()); return false; } @@ -376,9 +382,9 @@ bool ChatHandler::SetDataForCommandInTable(std::vector<ChatCommand>& table, char if (!cmd.empty()) { if (&table == &getCommandTable()) - TC_LOG_ERROR("sql.sql", "Table `command` have not existed command '%s', skip.", cmd.c_str()); + TC_LOG_ERROR("sql.sql", "Table `command` contains a non-existing command '%s', skipped.", cmd.c_str()); else - TC_LOG_ERROR("sql.sql", "Table `command` have not existed subcommand '%s' in command '%s', skip.", cmd.c_str(), fullcommand.c_str()); + TC_LOG_ERROR("sql.sql", "Table `command` contains a non-existing subcommand '%s' in command '%s', skipped.", cmd.c_str(), fullcommand.c_str()); } return false; @@ -444,7 +450,7 @@ Valid examples: if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY) < 3) { const char validSequence[6] = "cHhhr"; - const char* validSequenceIterator = validSequence; + char const* validSequenceIterator = validSequence; const std::string validCommands = "cHhr|"; while (*message) @@ -486,7 +492,7 @@ bool ChatHandler::ShowHelpForSubCommands(std::vector<ChatCommand> const& table, std::string list; for (uint32 i = 0; i < table.size(); ++i) { - // must be available (ignore handler existence for show command with possible available subcommands) + // must be available (ignore handler existence to show command with possible available subcommands) if (!isAvailable(table[i])) continue; @@ -519,13 +525,13 @@ bool ChatHandler::ShowHelpForSubCommands(std::vector<ChatCommand> const& table, return true; } -bool ChatHandler::ShowHelpForCommand(std::vector<ChatCommand> const& table, const char* cmd) +bool ChatHandler::ShowHelpForCommand(std::vector<ChatCommand> const& table, char const* cmd) { if (*cmd) { for (uint32 i = 0; i < table.size(); ++i) { - // must be available (ignore handler existence for show command with possible available subcommands) + // must be available (ignore handler existence to show command with possible available subcommands) if (!isAvailable(table[i])) continue; @@ -533,7 +539,7 @@ bool ChatHandler::ShowHelpForCommand(std::vector<ChatCommand> const& table, cons continue; // have subcommand - char const* subcmd = (*cmd) ? strtok(NULL, " ") : ""; + char const* subcmd = (*cmd) ? strtok(nullptr, " ") : ""; if (!table[i].ChildCommands.empty() && subcmd && *subcmd) { @@ -555,7 +561,7 @@ bool ChatHandler::ShowHelpForCommand(std::vector<ChatCommand> const& table, cons { for (uint32 i = 0; i < table.size(); ++i) { - // must be available (ignore handler existence for show command with possible available subcommands) + // must be available (ignore handler existence to show command with possible available subcommands) if (!isAvailable(table[i])) continue; @@ -688,7 +694,7 @@ size_t ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg chatType, Languag Player* ChatHandler::getSelectedPlayer() { if (!m_session) - return NULL; + return nullptr; ObjectGuid selected = m_session->GetPlayer()->GetTarget(); if (!selected) @@ -700,7 +706,7 @@ Player* ChatHandler::getSelectedPlayer() Unit* ChatHandler::getSelectedUnit() { if (!m_session) - return NULL; + return nullptr; if (Unit* selected = m_session->GetPlayer()->GetSelectedUnit()) return selected; @@ -711,7 +717,7 @@ Unit* ChatHandler::getSelectedUnit() WorldObject* ChatHandler::getSelectedObject() { if (!m_session) - return NULL; + return nullptr; ObjectGuid guid = m_session->GetPlayer()->GetTarget(); @@ -724,7 +730,7 @@ WorldObject* ChatHandler::getSelectedObject() Creature* ChatHandler::getSelectedCreature() { if (!m_session) - return NULL; + return nullptr; return ObjectAccessor::GetCreatureOrPetOrVehicle(*m_session->GetPlayer(), m_session->GetPlayer()->GetTarget()); } @@ -732,7 +738,7 @@ Creature* ChatHandler::getSelectedCreature() Player* ChatHandler::getSelectedPlayerOrSelf() { if (!m_session) - return NULL; + return nullptr; ObjectGuid selected = m_session->GetPlayer()->GetTarget(); if (!selected) @@ -751,14 +757,14 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* linkType, char** s { // skip empty if (!text) - return NULL; + return nullptr; // skip spaces while (*text == ' '||*text == '\t'||*text == '\b') ++text; if (!*text) - return NULL; + return nullptr; // return non link case if (text[0] != '|') @@ -770,28 +776,28 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* linkType, char** s char* check = strtok(text, "|"); // skip color if (!check) - return NULL; // end of data + return nullptr; // end of data - char* cLinkType = strtok(NULL, ":"); // linktype + char* cLinkType = strtok(nullptr, ":"); // linktype if (!cLinkType) - return NULL; // end of data + return nullptr; // end of data if (strcmp(cLinkType, linkType) != 0) { - strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after retturn from function + strtok(nullptr, " "); // skip link tail (to allow continue strtok(nullptr, s) use after retturn from function SendSysMessage(LANG_WRONG_LINK_TYPE); - return NULL; + return nullptr; } - char* cKeys = strtok(NULL, "|"); // extract keys and values - char* cKeysTail = strtok(NULL, ""); + char* cKeys = strtok(nullptr, "|"); // extract keys and values + char* cKeysTail = strtok(nullptr, ""); char* cKey = strtok(cKeys, ":|"); // extract key if (something1) - *something1 = strtok(NULL, ":|"); // extract something + *something1 = strtok(nullptr, ":|"); // extract something strtok(cKeysTail, "]"); // restart scan tail and skip name with possible spaces - strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function + strtok(nullptr, " "); // skip link tail (to allow continue strtok(nullptr, s) use after return from function return cKey; } @@ -799,14 +805,14 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* const* linkTypes, { // skip empty if (!text) - return NULL; + return nullptr; // skip spaces while (*text == ' '||*text == '\t'||*text == '\b') ++text; if (!*text) - return NULL; + return nullptr; // return non link case if (text[0] != '|') @@ -824,48 +830,48 @@ char* ChatHandler::extractKeyFromLink(char* text, char const* const* linkTypes, { char* check = strtok(text, "|"); // skip color if (!check) - return NULL; // end of data + return nullptr; // end of data - tail = strtok(NULL, ""); // tail + tail = strtok(nullptr, ""); // tail } else tail = text+1; // skip first | char* cLinkType = strtok(tail, ":"); // linktype if (!cLinkType) - return NULL; // end of data + return nullptr; // end of data for (int i = 0; linkTypes[i]; ++i) { if (strcmp(cLinkType, linkTypes[i]) == 0) { - char* cKeys = strtok(NULL, "|"); // extract keys and values - char* cKeysTail = strtok(NULL, ""); + char* cKeys = strtok(nullptr, "|"); // extract keys and values + char* cKeysTail = strtok(nullptr, ""); char* cKey = strtok(cKeys, ":|"); // extract key if (something1) - *something1 = strtok(NULL, ":|"); // extract something + *something1 = strtok(nullptr, ":|"); // extract something strtok(cKeysTail, "]"); // restart scan tail and skip name with possible spaces - strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function + strtok(nullptr, " "); // skip link tail (to allow continue strtok(nullptr, s) use after return from function if (found_idx) *found_idx = i; return cKey; } } - strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function + strtok(nullptr, " "); // skip link tail (to allow continue strtok(nullptr, s) use after return from function SendSysMessage(LANG_WRONG_LINK_TYPE); - return NULL; + return nullptr; } GameObject* ChatHandler::GetNearbyGameObject() { if (!m_session) - return NULL; + return nullptr; Player* pl = m_session->GetPlayer(); - GameObject* obj = NULL; + GameObject* obj = nullptr; Trinity::NearestGameObjectCheck check(*pl); Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectCheck> searcher(pl, obj, check); pl->VisitNearbyGridObject(SIZE_OF_GRIDS, searcher); @@ -875,7 +881,7 @@ GameObject* ChatHandler::GetNearbyGameObject() GameObject* ChatHandler::GetObjectGlobalyWithGuidOrNearWithDbGuid(ObjectGuid::LowType lowguid, uint32 entry) { if (!m_session) - return NULL; + return nullptr; Player* pl = m_session->GetPlayer(); @@ -920,7 +926,7 @@ uint32 ChatHandler::extractSpellIdFromLink(char* text) // number or [name] Shift-click form |color|Htalent:talent_id, rank|h[name]|h|r // number or [name] Shift-click form |color|Htrade:spell_id, skill_id, max_value, cur_value|h[name]|h|r int type = 0; - char* param1_str = NULL; + char* param1_str = nullptr; char* idS = extractKeyFromLink(text, spellKeys, &type, ¶m1_str); if (!idS) return 0; @@ -968,7 +974,7 @@ GameTele const* ChatHandler::extractGameTeleFromLink(char* text) // id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r char* cId = extractKeyFromLink(text, "Htele"); if (!cId) - return NULL; + return nullptr; // id case (explicit or from shift link) if (cId[0] >= '0' || cId[0] >= '9') @@ -1058,7 +1064,7 @@ std::string ChatHandler::extractPlayerNameFromLink(char* text) return name; } -bool ChatHandler::extractPlayerTarget(char* args, Player** player, ObjectGuid* player_guid /*=NULL*/, std::string* player_name /*= NULL*/) +bool ChatHandler::extractPlayerTarget(char* args, Player** player, ObjectGuid* player_guid /*=nullptr*/, std::string* player_name /*= nullptr*/) { if (args && *args) { @@ -1100,7 +1106,7 @@ bool ChatHandler::extractPlayerTarget(char* args, Player** player, ObjectGuid* p *player_name = pl ? pl->GetName() : ""; } - // some from req. data must be provided (note: name is empty if player not exist) + // some from req. data must be provided (note: name is empty if player does not exist) if ((!player || !*player) && (!player_guid || !*player_guid) && (!player_name || player_name->empty())) { SendSysMessage(LANG_PLAYER_NOT_FOUND); @@ -1114,12 +1120,12 @@ bool ChatHandler::extractPlayerTarget(char* args, Player** player, ObjectGuid* p void ChatHandler::extractOptFirstArg(char* args, char** arg1, char** arg2) { char* p1 = strtok(args, " "); - char* p2 = strtok(NULL, " "); + char* p2 = strtok(nullptr, " "); if (!p2) { p2 = p1; - p1 = NULL; + p1 = nullptr; } if (arg1) @@ -1132,7 +1138,7 @@ void ChatHandler::extractOptFirstArg(char* args, char** arg1, char** arg2) char* ChatHandler::extractQuotedArg(char* args) { if (!args || !*args) - return NULL; + return nullptr; if (*args == '"') return strtok(args+1, "\""); @@ -1145,9 +1151,9 @@ char* ChatHandler::extractQuotedArg(char* args) continue; } - // return NULL if we reached the end of the string + // return nullptr if we reached the end of the string if (!*args) - return NULL; + return nullptr; // since we skipped all spaces, we expect another token now if (*args == '"') @@ -1165,7 +1171,7 @@ char* ChatHandler::extractQuotedArg(char* args) return strtok(args + 1, "\""); } else - return NULL; + return nullptr; } } @@ -1217,9 +1223,9 @@ bool CliHandler::needReportToTarget(Player* /*chr*/) const return true; } -bool ChatHandler::GetPlayerGroupAndGUIDByName(const char* cname, Player*& player, Group*& group, ObjectGuid& guid, bool offline) +bool ChatHandler::GetPlayerGroupAndGUIDByName(char const* cname, Player*& player, Group*& group, ObjectGuid& guid, bool offline) { - player = NULL; + player = nullptr; guid.Clear(); if (cname) diff --git a/src/server/game/Chat/Chat.h b/src/server/game/Chat/Chat.h index 7ce0792cdf9..a700afdf97d 100644 --- a/src/server/game/Chat/Chat.h +++ b/src/server/game/Chat/Chat.h @@ -36,7 +36,7 @@ class WorldObject; struct GameTele; -class ChatCommand +class TC_GAME_API ChatCommand { typedef bool(*pHandler)(ChatHandler*, char const*); @@ -52,7 +52,7 @@ class ChatCommand std::vector<ChatCommand> ChildCommands; }; -class ChatHandler +class TC_GAME_API ChatHandler { public: WorldSession* GetSession() { return m_session; } @@ -67,7 +67,7 @@ class ChatHandler // Builds chat packet and returns receiver guid position in the packet to substitute in whisper builders static size_t BuildChatPacket(WorldPacket& data, ChatMsg chatType, Language language, WorldObject const* sender, WorldObject const* receiver, std::string const& message, uint32 achievementId = 0, std::string const& channelName = "", LocaleConstant locale = DEFAULT_LOCALE); - static char* LineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = NULL; return start; } + static char* LineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } // function with different implementation for chat/console virtual char const* GetTrinityString(uint32 entry) const; @@ -76,7 +76,7 @@ class ChatHandler void SendSysMessage(uint32 entry); template<typename... Args> - void PSendSysMessage(const char* fmt, Args&&... args) + void PSendSysMessage(char const* fmt, Args&&... args) { SendSysMessage(Trinity::StringFormat(fmt, std::forward<Args>(args)...).c_str()); } @@ -93,14 +93,15 @@ class ChatHandler return Trinity::StringFormat(GetTrinityString(entry), std::forward<Args>(args)...); } - bool ParseCommands(const char* text); + bool ParseCommands(char const* text); static std::vector<ChatCommand> const& getCommandTable(); + static void invalidateCommandTable(); - bool isValidChatMessage(const char* msg); + bool isValidChatMessage(char const* msg); void SendGlobalSysMessage(const char *str); - bool hasStringAbbr(const char* name, const char* part); + bool hasStringAbbr(char const* name, char const* part); // function with different implementation for chat/console virtual bool isAvailable(ChatCommand const& cmd) const; @@ -121,20 +122,20 @@ class ChatHandler // Returns either the selected player or self if there is no selected player Player* getSelectedPlayerOrSelf(); - char* extractKeyFromLink(char* text, char const* linkType, char** something1 = NULL); - char* extractKeyFromLink(char* text, char const* const* linkTypes, int* found_idx, char** something1 = NULL); + char* extractKeyFromLink(char* text, char const* linkType, char** something1 = nullptr); + char* extractKeyFromLink(char* text, char const* const* linkTypes, int* found_idx, char** something1 = nullptr); - // if args have single value then it return in arg2 and arg1 == NULL + // if args have single value then it return in arg2 and arg1 == nullptr void extractOptFirstArg(char* args, char** arg1, char** arg2); char* extractQuotedArg(char* args); uint32 extractSpellIdFromLink(char* text); ObjectGuid extractGuidFromLink(char* text); GameTele const* extractGameTeleFromLink(char* text); - bool GetPlayerGroupAndGUIDByName(const char* cname, Player*& player, Group*& group, ObjectGuid& guid, bool offline = false); + bool GetPlayerGroupAndGUIDByName(char const* cname, Player*& player, Group*& group, ObjectGuid& guid, bool offline = false); std::string extractPlayerNameFromLink(char* text); // select by arg (name/link) or in-game selection online/offline player or self if a creature is selected - bool extractPlayerTarget(char* args, Player** player, ObjectGuid* player_guid = NULL, std::string* player_name = NULL); + bool extractPlayerTarget(char* args, Player** player, ObjectGuid* player_guid = nullptr, std::string* player_name = nullptr); std::string playerLink(std::string const& name) const { return m_session ? "|cffffffff|Hplayer:"+name+"|h["+name+"]|h|r" : name; } std::string GetNameLink(Player* chr) const; @@ -143,25 +144,22 @@ class ChatHandler GameObject* GetObjectGlobalyWithGuidOrNearWithDbGuid(ObjectGuid::LowType lowguid, uint32 entry); bool HasSentErrorMessage() const { return sentErrorMessage; } void SetSentErrorMessage(bool val){ sentErrorMessage = val; } - static bool LoadCommandTable() { return load_command_table; } - static void SetLoadCommandTable(bool val) { load_command_table = val; } - bool ShowHelpForCommand(std::vector<ChatCommand> const& table, const char* cmd); + bool ShowHelpForCommand(std::vector<ChatCommand> const& table, char const* cmd); protected: - explicit ChatHandler() : m_session(NULL), sentErrorMessage(false) { } // for CLI subclass - static bool SetDataForCommandInTable(std::vector<ChatCommand>& table, const char* text, uint32 permission, std::string const& help, std::string const& fullcommand); - bool ExecuteCommandInTable(std::vector<ChatCommand> const& table, const char* text, std::string const& fullcmd); + explicit ChatHandler() : m_session(nullptr), sentErrorMessage(false) { } // for CLI subclass + static bool SetDataForCommandInTable(std::vector<ChatCommand>& table, char const* text, uint32 permission, std::string const& help, std::string const& fullcommand); + bool ExecuteCommandInTable(std::vector<ChatCommand> const& table, char const* text, std::string const& fullcmd); bool ShowHelpForSubCommands(std::vector<ChatCommand> const& table, char const* cmd, char const* subcmd); private: - WorldSession* m_session; // != NULL for chat command call and NULL for CLI command + WorldSession* m_session; // != nullptr for chat command call and nullptr for CLI command // common global flag - static bool load_command_table; bool sentErrorMessage; }; -class CliHandler : public ChatHandler +class TC_GAME_API CliHandler : public ChatHandler { public: typedef void Print(void*, char const*); diff --git a/src/server/game/Chat/ChatLink.cpp b/src/server/game/Chat/ChatLink.cpp index 3602b54bc44..92d69edb5e8 100644 --- a/src/server/game/Chat/ChatLink.cpp +++ b/src/server/game/Chat/ChatLink.cpp @@ -71,7 +71,7 @@ inline std::string ReadSkip(std::istringstream& iss, char term) return res; } -inline bool CheckDelimiter(std::istringstream& iss, char delimiter, const char* context) +inline bool CheckDelimiter(std::istringstream& iss, char delimiter, char const* context) { char c = iss.peek(); if (c != delimiter) @@ -96,7 +96,7 @@ inline bool ReadHex(std::istringstream& iss, uint32& res, uint32 length) #define DELIMITER ':' #define PIPE_CHAR '|' -bool ChatLink::ValidateName(char* buffer, const char* /*context*/) +bool ChatLink::ValidateName(char* buffer, char const* /*context*/) { _name = buffer; return true; @@ -170,7 +170,7 @@ bool ItemChatLink::Initialize(std::istringstream& iss) inline std::string ItemChatLink::FormatName(uint8 index, ItemLocale const* locale, char* const* suffixStrings) const { std::stringstream ss; - if (locale == NULL || index >= locale->Name.size()) + if (locale == nullptr || index >= locale->Name.size()) ss << _item->Name1; else ss << locale->Name[index]; @@ -179,13 +179,13 @@ inline std::string ItemChatLink::FormatName(uint8 index, ItemLocale const* local return ss.str(); } -bool ItemChatLink::ValidateName(char* buffer, const char* context) +bool ItemChatLink::ValidateName(char* buffer, char const* context) { ChatLink::ValidateName(buffer, context); - char* const* suffixStrings = _suffix ? _suffix->nameSuffix : (_property ? _property->nameSuffix : NULL); + char* const* suffixStrings = _suffix ? _suffix->nameSuffix : (_property ? _property->nameSuffix : nullptr); - bool res = (FormatName(LOCALE_enUS, NULL, suffixStrings) == buffer); + bool res = (FormatName(LOCALE_enUS, nullptr, suffixStrings) == buffer); if (!res) { ItemLocale const* il = sObjectMgr->GetItemLocale(_item->ItemId); @@ -239,7 +239,7 @@ bool QuestChatLink::Initialize(std::istringstream& iss) return true; } -bool QuestChatLink::ValidateName(char* buffer, const char* context) +bool QuestChatLink::ValidateName(char* buffer, char const* context) { ChatLink::ValidateName(buffer, context); @@ -280,7 +280,7 @@ bool SpellChatLink::Initialize(std::istringstream& iss) return true; } -bool SpellChatLink::ValidateName(char* buffer, const char* context) +bool SpellChatLink::ValidateName(char* buffer, char const* context) { ChatLink::ValidateName(buffer, context); @@ -373,7 +373,7 @@ bool AchievementChatLink::Initialize(std::istringstream& iss) return true; } -bool AchievementChatLink::ValidateName(char* buffer, const char* context) +bool AchievementChatLink::ValidateName(char* buffer, char const* context) { ChatLink::ValidateName(buffer, context); @@ -537,7 +537,7 @@ bool GlyphChatLink::Initialize(std::istringstream& iss) return true; } -LinkExtractor::LinkExtractor(const char* msg) : _iss(msg) { } +LinkExtractor::LinkExtractor(char const* msg) : _iss(msg) { } LinkExtractor::~LinkExtractor() { @@ -549,19 +549,19 @@ LinkExtractor::~LinkExtractor() bool LinkExtractor::IsValidMessage() { const char validSequence[6] = "cHhhr"; - const char* validSequenceIterator = validSequence; + char const* validSequenceIterator = validSequence; char buffer[256]; std::istringstream::pos_type startPos = 0; uint32 color = 0; - ChatLink* link = NULL; + ChatLink* link = nullptr; while (!_iss.eof()) { if (validSequence == validSequenceIterator) { - link = NULL; + link = nullptr; _iss.ignore(255, PIPE_CHAR); startPos = _iss.tellg() - std::istringstream::pos_type(1); } diff --git a/src/server/game/Chat/ChatLink.h b/src/server/game/Chat/ChatLink.h index 4adb61bbbf1..32ea4b73698 100644 --- a/src/server/game/Chat/ChatLink.h +++ b/src/server/game/Chat/ChatLink.h @@ -34,7 +34,7 @@ class Quest; /////////////////////////////////////////////////////////////////////////////////////////////////// // ChatLink - abstract base class for various links -class ChatLink +class TC_GAME_API ChatLink { public: ChatLink() : _color(0), _startPos(0), _endPos(0) { } @@ -44,7 +44,7 @@ public: void SetBounds(std::istringstream::pos_type startPos, std::istringstream::pos_type endPos) { _startPos = startPos; _endPos = endPos; } virtual bool Initialize(std::istringstream& iss) = 0; - virtual bool ValidateName(char* buffer, const char* context) = 0; + virtual bool ValidateName(char* buffer, char const* context) = 0; protected: uint32 _color; @@ -54,15 +54,15 @@ protected: }; // ItemChatLink - link to item -class ItemChatLink : public ChatLink +class TC_GAME_API ItemChatLink : public ChatLink { public: - ItemChatLink() : ChatLink(), _item(NULL), _suffix(NULL), _property(NULL) + ItemChatLink() : ChatLink(), _item(nullptr), _suffix(nullptr), _property(nullptr) { memset(_data, 0, sizeof(_data)); } virtual bool Initialize(std::istringstream& iss) override; - virtual bool ValidateName(char* buffer, const char* context) override; + virtual bool ValidateName(char* buffer, char const* context) override; protected: std::string FormatName(uint8 index, ItemLocale const* locale, char* const* suffixStrings) const; @@ -74,12 +74,12 @@ protected: }; // QuestChatLink - link to quest -class QuestChatLink : public ChatLink +class TC_GAME_API QuestChatLink : public ChatLink { public: QuestChatLink() : ChatLink(), _quest(nullptr), _questLevel(0) { } virtual bool Initialize(std::istringstream& iss) override; - virtual bool ValidateName(char* buffer, const char* context) override; + virtual bool ValidateName(char* buffer, char const* context) override; protected: Quest const* _quest; @@ -87,27 +87,27 @@ protected: }; // SpellChatLink - link to quest -class SpellChatLink : public ChatLink +class TC_GAME_API SpellChatLink : public ChatLink { public: SpellChatLink() : ChatLink(), _spell(nullptr) { } virtual bool Initialize(std::istringstream& iss) override; - virtual bool ValidateName(char* buffer, const char* context) override; + virtual bool ValidateName(char* buffer, char const* context) override; protected: SpellInfo const* _spell; }; // AchievementChatLink - link to quest -class AchievementChatLink : public ChatLink +class TC_GAME_API AchievementChatLink : public ChatLink { public: - AchievementChatLink() : ChatLink(), _guid(0), _achievement(NULL) + AchievementChatLink() : ChatLink(), _guid(0), _achievement(nullptr) { memset(_data, 0, sizeof(_data)); } virtual bool Initialize(std::istringstream& iss) override; - virtual bool ValidateName(char* buffer, const char* context) override; + virtual bool ValidateName(char* buffer, char const* context) override; protected: uint32 _guid; @@ -116,7 +116,7 @@ protected: }; // TradeChatLink - link to trade info -class TradeChatLink : public SpellChatLink +class TC_GAME_API TradeChatLink : public SpellChatLink { public: TradeChatLink() : SpellChatLink(), _minSkillLevel(0), _maxSkillLevel(0), _guid(0) { } @@ -129,7 +129,7 @@ private: }; // TalentChatLink - link to talent -class TalentChatLink : public SpellChatLink +class TC_GAME_API TalentChatLink : public SpellChatLink { public: TalentChatLink() : SpellChatLink(), _talentId(0), _rankId(0) { } @@ -141,7 +141,7 @@ private: }; // EnchantmentChatLink - link to enchantment -class EnchantmentChatLink : public SpellChatLink +class TC_GAME_API EnchantmentChatLink : public SpellChatLink { public: EnchantmentChatLink() : SpellChatLink() { } @@ -149,20 +149,20 @@ public: }; // GlyphChatLink - link to glyph -class GlyphChatLink : public SpellChatLink +class TC_GAME_API GlyphChatLink : public SpellChatLink { public: - GlyphChatLink() : SpellChatLink(), _slotId(0), _glyph(NULL) { } + GlyphChatLink() : SpellChatLink(), _slotId(0), _glyph(nullptr) { } virtual bool Initialize(std::istringstream& iss) override; private: uint32 _slotId; GlyphPropertiesEntry const* _glyph; }; -class LinkExtractor +class TC_GAME_API LinkExtractor { public: - explicit LinkExtractor(const char* msg); + explicit LinkExtractor(char const* msg); ~LinkExtractor(); bool IsValidMessage(); diff --git a/src/server/game/Combat/HostileRefManager.h b/src/server/game/Combat/HostileRefManager.h index 96152ed46f7..855f9e3d272 100644 --- a/src/server/game/Combat/HostileRefManager.h +++ b/src/server/game/Combat/HostileRefManager.h @@ -29,7 +29,7 @@ class SpellInfo; //================================================= -class HostileRefManager : public RefManager<Unit, ThreatManager> +class TC_GAME_API HostileRefManager : public RefManager<Unit, ThreatManager> { private: Unit* iOwner; diff --git a/src/server/game/Combat/ThreatManager.cpp b/src/server/game/Combat/ThreatManager.cpp index 588e7b1a93b..9767d69e2aa 100644 --- a/src/server/game/Combat/ThreatManager.cpp +++ b/src/server/game/Combat/ThreatManager.cpp @@ -335,7 +335,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR { // current victim is a second choice target, so don't compare threat with it below if (currentRef == currentVictim) - currentVictim = NULL; + currentVictim = nullptr; ++iter; continue; } @@ -437,12 +437,15 @@ void ThreatManager::_addThreat(Unit* victim, float threat) if (!ref) // there was no ref => create a new one { + bool isFirst = iThreatContainer.empty(); // threat has to be 0 here HostileReference* hostileRef = new HostileReference(victim, this, 0); iThreatContainer.addReference(hostileRef); hostileRef->addThreat(threat); // now we add the real threat if (victim->GetTypeId() == TYPEID_PLAYER && victim->ToPlayer()->IsGameMaster()) hostileRef->setOnlineOfflineState(false); // GM is always offline + else if (isFirst) + setCurrentVictim(hostileRef); } } diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index 7d20e99c128..a68d803304d 100644 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -39,14 +39,14 @@ class SpellInfo; //============================================================== // Class to calculate the real threat based -struct ThreatCalcHelper +struct TC_GAME_API ThreatCalcHelper { static float calcThreat(Unit* hatedUnit, Unit* hatingUnit, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); static bool isValidProcess(Unit* hatedUnit, Unit* hatingUnit, SpellInfo const* threatSpell = NULL); }; //============================================================== -class HostileReference : public Reference<Unit, ThreatManager> +class TC_GAME_API HostileReference : public Reference<Unit, ThreatManager> { public: HostileReference(Unit* refUnit, ThreatManager* threatManager, float threat); @@ -141,7 +141,7 @@ class HostileReference : public Reference<Unit, ThreatManager> //============================================================== class ThreatManager; -class ThreatContainer +class TC_GAME_API ThreatContainer { friend class ThreatManager; @@ -169,7 +169,7 @@ class ThreatContainer HostileReference* getMostHated() const { - return iThreatList.empty() ? NULL : iThreatList.front(); + return iThreatList.empty() ? nullptr : iThreatList.front(); } HostileReference* getReferenceByTarget(Unit* victim) const; @@ -198,7 +198,7 @@ class ThreatContainer //================================================= -class ThreatManager +class TC_GAME_API ThreatManager { public: friend class HostileReference; diff --git a/src/server/game/Combat/UnitEvents.h b/src/server/game/Combat/UnitEvents.h index e501cdaa4a2..f50edcf3c7d 100644 --- a/src/server/game/Combat/UnitEvents.h +++ b/src/server/game/Combat/UnitEvents.h @@ -81,7 +81,7 @@ class UnitBaseEvent //============================================================== -class ThreatRefStatusChangeEvent : public UnitBaseEvent +class TC_GAME_API ThreatRefStatusChangeEvent : public UnitBaseEvent { private: HostileReference* iHostileReference; diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index 4215a3a5d02..6317fae2767 100644 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -55,7 +55,8 @@ char const* const ConditionMgr::StaticSourceTypeData[CONDITION_SOURCE_TYPE_MAX] "SmartScript", "Npc Vendor", "Spell Proc", - "Phase Def" + "Terrain Swap", + "Phase" }; ConditionMgr::ConditionTypeInfo const ConditionMgr::StaticConditionTypeData[CONDITION_MAX] = @@ -100,7 +101,10 @@ ConditionMgr::ConditionTypeInfo const ConditionMgr::StaticConditionTypeData[COND { "Health Value", true, true, false }, { "Health Pct", true, true, false }, { "Realm Achievement", true, false, false }, - { "In Water", false, false, false } + { "In Water", false, false, false }, + { "Terrain Swap", false, false, false }, + { "Sit/stand state", true, true, false }, + { "Daily Quest Completed",true, false, false } }; // Checks if object meets the condition @@ -432,6 +436,25 @@ bool Condition::Meets(ConditionSourceInfo& sourceInfo) const condMeets = unit->IsInWater(); break; } + case CONDITION_STAND_STATE: + { + if (Unit* unit = object->ToUnit()) + { + if (ConditionValue1 == 0) + condMeets = (unit->GetStandState() == ConditionValue2); + else if (ConditionValue2 == 0) + condMeets = unit->IsStandState(); + else if (ConditionValue2 == 1) + condMeets = unit->IsSitState(); + } + break; + } + case CONDITION_DAILY_QUEST_DONE: + { + if (Player* player = object->ToPlayer()) + condMeets = player->IsDailyQuestDone(ConditionValue1); + break; + } default: condMeets = false; break; @@ -602,6 +625,12 @@ uint32 Condition::GetSearcherTypeMaskForCondition() const case CONDITION_IN_WATER: mask |= GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER; break; + case CONDITION_STAND_STATE: + mask |= GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER; + break; + case CONDITION_DAILY_QUEST_DONE: + mask |= GRID_MAP_TYPE_MASK_PLAYER; + break; default: ASSERT(false && "Condition::GetSearcherTypeMaskForCondition - missing condition handling!"); break; @@ -719,7 +748,7 @@ bool ConditionMgr::IsObjectMeetToConditionList(ConditionSourceInfo& sourceInfo, //! If not found, add an entry in the store and set to true (placeholder) if (itr == elseGroupStore.end()) elseGroupStore[condition->ElseGroup] = true; - else if (!(*itr).second) + else if (!(*itr).second) //! If another condition in this group was unmatched before this, don't bother checking (the group is false anyway) continue; if (condition->ReferenceId)//handle reference @@ -909,6 +938,12 @@ bool ConditionMgr::IsObjectMeetingVendorItemConditions(uint32 creatureId, uint32 return true; } +ConditionMgr* ConditionMgr::instance() +{ + static ConditionMgr instance; + return &instance; +} + void ConditionMgr::LoadConditions(bool isReload) { uint32 oldMSTime = getMSTime(); @@ -1217,7 +1252,7 @@ bool ConditionMgr::addToGossipMenuItems(Condition* cond) const bool ConditionMgr::addToSpellImplicitTargetConditions(Condition* cond) const { uint32 conditionEffMask = cond->SourceGroup; - SpellInfo* spellInfo = const_cast<SpellInfo*>(sSpellMgr->EnsureSpellInfo(cond->SourceEntry)); + SpellInfo* spellInfo = const_cast<SpellInfo*>(sSpellMgr->AssertSpellInfo(cond->SourceEntry)); std::list<uint32> sharedMasks; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { @@ -1633,9 +1668,14 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) const } break; } - case CONDITION_SOURCE_TYPE_PHASE_DEFINITION: + case CONDITION_SOURCE_TYPE_TERRAIN_SWAP: + { + TC_LOG_ERROR("sql.sql", "CONDITION_SOURCE_TYPE_TERRAIN_SWAP: is only for 6.x branch, skipped"); + return false; + } + case CONDITION_SOURCE_TYPE_PHASE: { - TC_LOG_ERROR("sql.sql", "CONDITION_SOURCE_TYPE_PHASE_DEFINITION:: is only for 4.3.4 branch, skipped"); + TC_LOG_ERROR("sql.sql", "CONDITION_SOURCE_TYPE_PHASE: is only for 6.x branch, skipped"); return false; } case CONDITION_SOURCE_TYPE_GOSSIP_MENU: @@ -1653,7 +1693,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) const { if (cond->ConditionType == CONDITION_NONE || cond->ConditionType >= CONDITION_MAX) { - TC_LOG_ERROR("sql.sql", "%s Invalid ConditionType in `condition` table, ignoring.", cond->ToString().c_str()); + TC_LOG_ERROR("sql.sql", "%s Invalid ConditionType in `condition` table, ignoring.", cond->ToString(true).c_str()); return false; } @@ -1761,6 +1801,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) const case CONDITION_QUESTTAKEN: case CONDITION_QUEST_NONE: case CONDITION_QUEST_COMPLETE: + case CONDITION_DAILY_QUEST_DONE: { if (!sObjectMgr->GetQuestTemplate(cond->ConditionValue1)) { @@ -2090,6 +2131,31 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) const } case CONDITION_IN_WATER: break; + case CONDITION_TERRAIN_SWAP: + TC_LOG_ERROR("sql.sql", "%s is not valid for this branch, skipped.", cond->ToString(true).c_str()); + return false; + case CONDITION_STAND_STATE: + { + bool valid = false; + switch (cond->ConditionValue1) + { + case 0: + valid = cond->ConditionValue2 <= UNIT_STAND_STATE_SUBMERGED; + break; + case 1: + valid = cond->ConditionValue2 <= 1; + break; + default: + valid = false; + break; + } + if (!valid) + { + TC_LOG_ERROR("sql.sql", "%s has non-existing stand state (%u,%u), skipped.", cond->ToString(true).c_str(), cond->ConditionValue1, cond->ConditionValue2); + return false; + } + break; + } default: break; } diff --git a/src/server/game/Conditions/ConditionMgr.h b/src/server/game/Conditions/ConditionMgr.h index 35096ae18ff..4ec2be0753a 100644 --- a/src/server/game/Conditions/ConditionMgr.h +++ b/src/server/game/Conditions/ConditionMgr.h @@ -71,7 +71,10 @@ enum ConditionTypes CONDITION_HP_PCT = 38, // hpPct ComparisonType 0 true if unit's hp matches given pct CONDITION_REALM_ACHIEVEMENT = 39, // achievement_id 0 0 true if realm achievement is complete CONDITION_IN_WATER = 40, // 0 0 0 true if unit in water - CONDITION_MAX = 41 // MAX + CONDITION_TERRAIN_SWAP = 41, // only for 6.x + CONDITION_STAND_STATE = 42, // stateType state 0 true if unit matches specified sitstate (0,x: has exactly state x; 1,0: any standing state; 1,1: any sitting state;) + CONDITION_DAILY_QUEST_DONE = 43, // quest id 0 0 true if daily quest has been completed for the day + CONDITION_MAX = 44 // MAX }; /*! Documentation on implementing a new ConditionSourceType: @@ -128,8 +131,9 @@ enum ConditionSourceType CONDITION_SOURCE_TYPE_SMART_EVENT = 22, CONDITION_SOURCE_TYPE_NPC_VENDOR = 23, CONDITION_SOURCE_TYPE_SPELL_PROC = 24, - CONDITION_SOURCE_TYPE_PHASE_DEFINITION = 25, // only 4.3.4 - CONDITION_SOURCE_TYPE_MAX = 26 // MAX + CONDITION_SOURCE_TYPE_TERRAIN_SWAP = 25, // only 6.x + CONDITION_SOURCE_TYPE_PHASE = 26, // only 6.x + CONDITION_SOURCE_TYPE_MAX = 27 // MAX }; enum RelationType @@ -156,7 +160,7 @@ enum MaxConditionTargets MAX_CONDITION_TARGETS = 3 }; -struct ConditionSourceInfo +struct TC_GAME_API ConditionSourceInfo { WorldObject* mConditionTargets[MAX_CONDITION_TARGETS]; // an array of targets available for conditions Condition const* mLastFailedCondition; @@ -169,7 +173,7 @@ struct ConditionSourceInfo } }; -struct Condition +struct TC_GAME_API Condition { ConditionSourceType SourceType; //SourceTypeOrReferenceId uint32 SourceGroup; @@ -221,18 +225,14 @@ typedef std::unordered_map<uint32, ConditionsByEntryMap> ConditionEntriesByCreat typedef std::unordered_map<std::pair<int32, uint32 /*SAI source_type*/>, ConditionsByEntryMap> SmartEventConditionContainer; typedef std::unordered_map<uint32, ConditionContainer> ConditionReferenceContainer;//only used for references -class ConditionMgr +class TC_GAME_API ConditionMgr { private: ConditionMgr(); ~ConditionMgr(); public: - static ConditionMgr* instance() - { - static ConditionMgr instance; - return &instance; - } + static ConditionMgr* instance(); void LoadConditions(bool isReload = false); bool isConditionTypeValid(Condition* cond) const; diff --git a/src/server/game/Conditions/DisableMgr.h b/src/server/game/Conditions/DisableMgr.h index e74b7a9c319..cae1e0329e8 100644 --- a/src/server/game/Conditions/DisableMgr.h +++ b/src/server/game/Conditions/DisableMgr.h @@ -57,11 +57,11 @@ enum MMapDisableTypes namespace DisableMgr { - void LoadDisables(); - bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags = 0); - void CheckQuestDisables(); - bool IsVMAPDisabledFor(uint32 entry, uint8 flags); - bool IsPathfindingEnabled(uint32 mapId); + TC_GAME_API void LoadDisables(); + TC_GAME_API bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags = 0); + TC_GAME_API void CheckQuestDisables(); + TC_GAME_API bool IsVMAPDisabledFor(uint32 entry, uint8 flags); + TC_GAME_API bool IsPathfindingEnabled(uint32 mapId); } #endif //TRINITY_DISABLEMGR_H diff --git a/src/server/game/DataStores/DBCEnums.h b/src/server/game/DataStores/DBCEnums.h index f0ea5b4a5f1..cb2f26e567f 100644 --- a/src/server/game/DataStores/DBCEnums.h +++ b/src/server/game/DataStores/DBCEnums.h @@ -19,6 +19,22 @@ #ifndef DBCENUMS_H #define DBCENUMS_H +#pragma pack(push, 1) + +struct DBCPosition2D +{ + float X; + float Y; +}; + +struct DBCPosition3D +{ + float X; + float Y; + float Z; +}; + +#pragma pack(pop) enum LevelLimit { // Client expected level limitation, like as used in DBC item max levels for "until max player level" diff --git a/src/server/game/DataStores/DBCStores.cpp b/src/server/game/DataStores/DBCStores.cpp index 6c51c71fe7b..051b5e824bf 100644 --- a/src/server/game/DataStores/DBCStores.cpp +++ b/src/server/game/DataStores/DBCStores.cpp @@ -25,7 +25,7 @@ #include "Timer.h" #include "ObjectDefines.h" -#include <boost/regex.hpp> +#include <regex> #include <map> typedef std::map<uint16, uint32> AreaFlagByAreaID; @@ -73,6 +73,7 @@ DBCStorage <CharTitlesEntry> sCharTitlesStore(CharTitlesEntryfmt); DBCStorage <ChatChannelsEntry> sChatChannelsStore(ChatChannelsEntryfmt); DBCStorage <ChrClassesEntry> sChrClassesStore(ChrClassesEntryfmt); DBCStorage <ChrRacesEntry> sChrRacesStore(ChrRacesEntryfmt); +DBCStorage <CinematicCameraEntry> sCinematicCameraStore(CinematicCameraEntryfmt); DBCStorage <CinematicSequencesEntry> sCinematicSequencesStore(CinematicSequencesEntryfmt); DBCStorage <CreatureDisplayInfoEntry> sCreatureDisplayInfoStore(CreatureDisplayInfofmt); DBCStorage <CreatureDisplayInfoExtraEntry> sCreatureDisplayInfoExtraStore(CreatureDisplayInfoExtrafmt); @@ -144,7 +145,7 @@ DBCStorage <MovieEntry> sMovieStore(MovieEntryfmt); DBCStorage<NamesProfanityEntry> sNamesProfanityStore(NamesProfanityEntryfmt); DBCStorage<NamesReservedEntry> sNamesReservedStore(NamesReservedEntryfmt); -typedef std::array<std::vector<boost::regex>, TOTAL_LOCALES> NameValidationRegexContainer; +typedef std::array<std::vector<std::wregex>, TOTAL_LOCALES> NameValidationRegexContainer; NameValidationRegexContainer NamesProfaneValidators; NameValidationRegexContainer NamesReservedValidators; @@ -263,7 +264,7 @@ inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCSt if (FILE* f = fopen(dbcFilename.c_str(), "rb")) { std::ostringstream stream; - stream << dbcFilename << " exists, and has " << storage.GetFieldCount() << " field(s) (expected " << strlen(storage.GetFormat()) << "). Extracted file might be from wrong client version or a database-update has been forgotten."; + stream << dbcFilename << " exists, and has " << storage.GetFieldCount() << " field(s) (expected " << strlen(storage.GetFormat()) << "). Extracted file might be from wrong client version or a database-update has been forgotten. Search on forum for TCE00008 for more info."; std::string buf = stream.str(); errors.push_back(buf); fclose(f); @@ -311,6 +312,7 @@ void LoadDBCStores(const std::string& dataPath) LoadDBC(availableDbcLocales, bad_dbc_files, sChatChannelsStore, dbcPath, "ChatChannels.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sChrClassesStore, dbcPath, "ChrClasses.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sChrRacesStore, dbcPath, "ChrRaces.dbc"); + LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicCameraStore, dbcPath, "CinematicCamera.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicSequencesStore, dbcPath, "CinematicSequences.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoStore, dbcPath, "CreatureDisplayInfo.dbc"); LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoExtraStore, dbcPath, "CreatureDisplayInfoExtra.dbc"); @@ -408,11 +410,14 @@ void LoadDBCStores(const std::string& dataPath) continue; ASSERT(namesProfanity->Language < TOTAL_LOCALES || namesProfanity->Language == -1); + std::wstring wname; + ASSERT(Utf8toWStr(namesProfanity->Name, wname)); + if (namesProfanity->Language != -1) - NamesProfaneValidators[namesProfanity->Language].emplace_back(namesProfanity->Name, boost::regex::perl | boost::regex::icase | boost::regex::optimize); + NamesProfaneValidators[namesProfanity->Language].emplace_back(wname, std::regex::icase | std::regex::optimize); else for (uint32 i = 0; i < TOTAL_LOCALES; ++i) - NamesProfaneValidators[i].emplace_back(namesProfanity->Name, boost::regex::perl | boost::regex::icase | boost::regex::optimize); + NamesProfaneValidators[i].emplace_back(wname, std::regex::icase | std::regex::optimize); } for (uint32 i = 0; i < sNamesReservedStore.GetNumRows(); ++i) @@ -422,11 +427,14 @@ void LoadDBCStores(const std::string& dataPath) continue; ASSERT(namesReserved->Language < TOTAL_LOCALES || namesReserved->Language == -1); + std::wstring wname; + ASSERT(Utf8toWStr(namesReserved->Name, wname)); + if (namesReserved->Language != -1) - NamesReservedValidators[namesReserved->Language].emplace_back(namesReserved->Name, boost::regex::perl | boost::regex::icase | boost::regex::optimize); + NamesReservedValidators[namesReserved->Language].emplace_back(wname, std::regex::icase | std::regex::optimize); else for (uint32 i = 0; i < TOTAL_LOCALES; ++i) - NamesReservedValidators[i].emplace_back(namesReserved->Name, boost::regex::perl | boost::regex::icase | boost::regex::optimize); + NamesReservedValidators[i].emplace_back(wname, std::regex::icase | std::regex::optimize); } @@ -998,18 +1006,18 @@ SkillRaceClassInfoEntry const* GetSkillRaceClassInfo(uint32 skill, uint8 race, u return NULL; } -ResponseCodes ValidateName(std::string const& name, LocaleConstant locale) +ResponseCodes ValidateName(std::wstring const& name, LocaleConstant locale) { if (locale >= TOTAL_LOCALES) return RESPONSE_FAILURE; - for (boost::regex const& regex : NamesProfaneValidators[locale]) - if (boost::regex_search(name, regex)) + for (std::wregex const& regex : NamesProfaneValidators[locale]) + if (std::regex_search(name, regex)) return CHAR_NAME_PROFANE; // regexes at TOTAL_LOCALES are loaded from NamesReserved which is not locale specific - for (boost::regex const& regex : NamesReservedValidators[locale]) - if (boost::regex_search(name, regex)) + for (std::wregex const& regex : NamesReservedValidators[locale]) + if (std::regex_search(name, regex)) return CHAR_NAME_RESERVED; return CHAR_NAME_SUCCESS; @@ -1017,5 +1025,6 @@ ResponseCodes ValidateName(std::string const& name, LocaleConstant locale) EmotesTextSoundEntry const* FindTextSoundEmoteFor(uint32 emote, uint32 race, uint32 gender) { - return sEmotesTextSoundMap[EmotesTextSoundKey(emote, race, gender)]; + auto itr = sEmotesTextSoundMap.find(EmotesTextSoundKey(emote, race, gender)); + return itr != sEmotesTextSoundMap.end() ? itr->second : nullptr; } diff --git a/src/server/game/DataStores/DBCStores.h b/src/server/game/DataStores/DBCStores.h index 56ee1f618dd..128ff7ad1b8 100644 --- a/src/server/game/DataStores/DBCStores.h +++ b/src/server/game/DataStores/DBCStores.h @@ -27,18 +27,18 @@ #include <list> typedef std::list<uint32> SimpleFactionsList; -SimpleFactionsList const* GetFactionTeamList(uint32 faction); +TC_GAME_API SimpleFactionsList const* GetFactionTeamList(uint32 faction); -char* GetPetName(uint32 petfamily, uint32 dbclang); -uint32 GetTalentSpellCost(uint32 spellId); -TalentSpellPos const* GetTalentSpellPos(uint32 spellId); +TC_GAME_API char* GetPetName(uint32 petfamily, uint32 dbclang); +TC_GAME_API uint32 GetTalentSpellCost(uint32 spellId); +TC_GAME_API TalentSpellPos const* GetTalentSpellPos(uint32 spellId); -char const* GetRaceName(uint8 race, uint8 locale); -char const* GetClassName(uint8 class_, uint8 locale); +TC_GAME_API char const* GetRaceName(uint8 race, uint8 locale); +TC_GAME_API char const* GetClassName(uint8 class_, uint8 locale); -WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, int32 adtid, int32 groupid); +TC_GAME_API WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, int32 adtid, int32 groupid); -uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId); +TC_GAME_API uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId); enum ContentLevels { @@ -46,154 +46,155 @@ enum ContentLevels CONTENT_61_70, CONTENT_71_80 }; -ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId); +TC_GAME_API ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId); -bool IsTotemCategoryCompatiableWith(uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId); +TC_GAME_API bool IsTotemCategoryCompatiableWith(uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId); -void Zone2MapCoordinates(float &x, float &y, uint32 zone); -void Map2ZoneCoordinates(float &x, float &y, uint32 zone); +TC_GAME_API void Zone2MapCoordinates(float &x, float &y, uint32 zone); +TC_GAME_API void Map2ZoneCoordinates(float &x, float &y, uint32 zone); typedef std::map<uint32/*pair32(map, diff)*/, MapDifficulty> MapDifficultyMap; -MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty); -MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty); +TC_GAME_API MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty); +TC_GAME_API MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty); -uint32 const* /*[MAX_TALENT_TABS]*/ GetTalentTabPages(uint8 cls); +TC_GAME_API uint32 const* /*[MAX_TALENT_TABS]*/ GetTalentTabPages(uint8 cls); -uint32 GetLiquidFlags(uint32 liquidType); +TC_GAME_API uint32 GetLiquidFlags(uint32 liquidType); -PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 level); -PvPDifficultyEntry const* GetBattlegroundBracketById(uint32 mapid, BattlegroundBracketId id); +TC_GAME_API PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 level); +TC_GAME_API PvPDifficultyEntry const* GetBattlegroundBracketById(uint32 mapid, BattlegroundBracketId id); -CharStartOutfitEntry const* GetCharStartOutfitEntry(uint8 race, uint8 class_, uint8 gender); -CharSectionsEntry const* GetCharSectionEntry(uint8 race, CharSectionType genType, uint8 gender, uint8 type, uint8 color); +TC_GAME_API CharStartOutfitEntry const* GetCharStartOutfitEntry(uint8 race, uint8 class_, uint8 gender); +TC_GAME_API CharSectionsEntry const* GetCharSectionEntry(uint8 race, CharSectionType genType, uint8 gender, uint8 type, uint8 color); -LFGDungeonEntry const* GetLFGDungeon(uint32 mapId, Difficulty difficulty); +TC_GAME_API LFGDungeonEntry const* GetLFGDungeon(uint32 mapId, Difficulty difficulty); -uint32 GetDefaultMapLight(uint32 mapId); +TC_GAME_API uint32 GetDefaultMapLight(uint32 mapId); typedef std::unordered_multimap<uint32, SkillRaceClassInfoEntry const*> SkillRaceClassInfoMap; typedef std::pair<SkillRaceClassInfoMap::iterator, SkillRaceClassInfoMap::iterator> SkillRaceClassInfoBounds; -SkillRaceClassInfoEntry const* GetSkillRaceClassInfo(uint32 skill, uint8 race, uint8 class_); - -ResponseCodes ValidateName(std::string const& name, LocaleConstant locale); - -EmotesTextSoundEntry const* FindTextSoundEmoteFor(uint32 emote, uint32 race, uint32 gender); - -extern DBCStorage <AchievementEntry> sAchievementStore; -extern DBCStorage <AchievementCriteriaEntry> sAchievementCriteriaStore; -extern DBCStorage <AreaTableEntry> sAreaTableStore; -extern DBCStorage <AreaGroupEntry> sAreaGroupStore; -extern DBCStorage <AreaPOIEntry> sAreaPOIStore; -extern DBCStorage <AreaTriggerEntry> sAreaTriggerStore; -extern DBCStorage <AuctionHouseEntry> sAuctionHouseStore; -extern DBCStorage <BankBagSlotPricesEntry> sBankBagSlotPricesStore; -extern DBCStorage <BannedAddOnsEntry> sBannedAddOnsStore; -extern DBCStorage <BarberShopStyleEntry> sBarberShopStyleStore; -extern DBCStorage <BattlemasterListEntry> sBattlemasterListStore; -extern DBCStorage <ChatChannelsEntry> sChatChannelsStore; -extern DBCStorage <CharStartOutfitEntry> sCharStartOutfitStore; -extern DBCStorage <CharSectionsEntry> sCharSectionsStore; -extern DBCStorage <CharTitlesEntry> sCharTitlesStore; -extern DBCStorage <ChrClassesEntry> sChrClassesStore; -extern DBCStorage <ChrRacesEntry> sChrRacesStore; -extern DBCStorage <CinematicSequencesEntry> sCinematicSequencesStore; -extern DBCStorage <CreatureDisplayInfoEntry> sCreatureDisplayInfoStore; -extern DBCStorage <CreatureDisplayInfoExtraEntry> sCreatureDisplayInfoExtraStore; -extern DBCStorage <CreatureFamilyEntry> sCreatureFamilyStore; -extern DBCStorage <CreatureModelDataEntry> sCreatureModelDataStore; -extern DBCStorage <CreatureSpellDataEntry> sCreatureSpellDataStore; -extern DBCStorage <CreatureTypeEntry> sCreatureTypeStore; -extern DBCStorage <CurrencyTypesEntry> sCurrencyTypesStore; -extern DBCStorage <DestructibleModelDataEntry> sDestructibleModelDataStore; -extern DBCStorage <DungeonEncounterEntry> sDungeonEncounterStore; -extern DBCStorage <DurabilityCostsEntry> sDurabilityCostsStore; -extern DBCStorage <DurabilityQualityEntry> sDurabilityQualityStore; -extern DBCStorage <EmotesEntry> sEmotesStore; -extern DBCStorage <EmotesTextEntry> sEmotesTextStore; -extern DBCStorage <EmotesTextSoundEntry> sEmotesTextSoundStore; -extern DBCStorage <FactionEntry> sFactionStore; -extern DBCStorage <FactionTemplateEntry> sFactionTemplateStore; -extern DBCStorage <GameObjectDisplayInfoEntry> sGameObjectDisplayInfoStore; -extern DBCStorage <GemPropertiesEntry> sGemPropertiesStore; -extern DBCStorage <GlyphPropertiesEntry> sGlyphPropertiesStore; -extern DBCStorage <GlyphSlotEntry> sGlyphSlotStore; - -extern DBCStorage <GtBarberShopCostBaseEntry> sGtBarberShopCostBaseStore; -extern DBCStorage <GtCombatRatingsEntry> sGtCombatRatingsStore; -extern DBCStorage <GtChanceToMeleeCritBaseEntry> sGtChanceToMeleeCritBaseStore; -extern DBCStorage <GtChanceToMeleeCritEntry> sGtChanceToMeleeCritStore; -extern DBCStorage <GtChanceToSpellCritBaseEntry> sGtChanceToSpellCritBaseStore; -extern DBCStorage <GtChanceToSpellCritEntry> sGtChanceToSpellCritStore; -extern DBCStorage <GtNPCManaCostScalerEntry> sGtNPCManaCostScalerStore; -extern DBCStorage <GtOCTClassCombatRatingScalarEntry> sGtOCTClassCombatRatingScalarStore; -extern DBCStorage <GtOCTRegenHPEntry> sGtOCTRegenHPStore; -//extern DBCStorage <GtOCTRegenMPEntry> sGtOCTRegenMPStore; -- not used currently -extern DBCStorage <GtRegenHPPerSptEntry> sGtRegenHPPerSptStore; -extern DBCStorage <GtRegenMPPerSptEntry> sGtRegenMPPerSptStore; -extern DBCStorage <HolidaysEntry> sHolidaysStore; -extern DBCStorage <ItemEntry> sItemStore; -extern DBCStorage <ItemBagFamilyEntry> sItemBagFamilyStore; -//extern DBCStorage <ItemDisplayInfoEntry> sItemDisplayInfoStore; -- not used currently -extern DBCStorage <ItemExtendedCostEntry> sItemExtendedCostStore; -extern DBCStorage <ItemLimitCategoryEntry> sItemLimitCategoryStore; -extern DBCStorage <ItemRandomPropertiesEntry> sItemRandomPropertiesStore; -extern DBCStorage <ItemRandomSuffixEntry> sItemRandomSuffixStore; -extern DBCStorage <ItemSetEntry> sItemSetStore; -extern DBCStorage <LFGDungeonEntry> sLFGDungeonStore; -extern DBCStorage <LiquidTypeEntry> sLiquidTypeStore; -extern DBCStorage <LockEntry> sLockStore; -extern DBCStorage <MailTemplateEntry> sMailTemplateStore; -extern DBCStorage <MapEntry> sMapStore; -//extern DBCStorage <MapDifficultyEntry> sMapDifficultyStore; -- use GetMapDifficultyData insteed -extern MapDifficultyMap sMapDifficultyMap; -extern DBCStorage <MovieEntry> sMovieStore; -extern DBCStorage <OverrideSpellDataEntry> sOverrideSpellDataStore; -extern DBCStorage <PowerDisplayEntry> sPowerDisplayStore; -extern DBCStorage <QuestSortEntry> sQuestSortStore; -extern DBCStorage <QuestXPEntry> sQuestXPStore; -extern DBCStorage <QuestFactionRewEntry> sQuestFactionRewardStore; -extern DBCStorage <RandomPropertiesPointsEntry> sRandomPropertiesPointsStore; -extern DBCStorage <ScalingStatDistributionEntry> sScalingStatDistributionStore; -extern DBCStorage <ScalingStatValuesEntry> sScalingStatValuesStore; -extern DBCStorage <SkillLineEntry> sSkillLineStore; -extern DBCStorage <SkillLineAbilityEntry> sSkillLineAbilityStore; -extern DBCStorage <SkillTiersEntry> sSkillTiersStore; -extern DBCStorage <SoundEntriesEntry> sSoundEntriesStore; -extern DBCStorage <SpellCastTimesEntry> sSpellCastTimesStore; -extern DBCStorage <SpellCategoryEntry> sSpellCategoryStore; -extern DBCStorage <SpellDifficultyEntry> sSpellDifficultyStore; -extern DBCStorage <SpellDurationEntry> sSpellDurationStore; -extern DBCStorage <SpellFocusObjectEntry> sSpellFocusObjectStore; -extern DBCStorage <SpellItemEnchantmentEntry> sSpellItemEnchantmentStore; -extern DBCStorage <SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore; -extern PetFamilySpellsStore sPetFamilySpellsStore; -extern DBCStorage <SpellRadiusEntry> sSpellRadiusStore; -extern DBCStorage <SpellRangeEntry> sSpellRangeStore; -extern DBCStorage <SpellRuneCostEntry> sSpellRuneCostStore; -extern DBCStorage <SpellShapeshiftEntry> sSpellShapeshiftStore; -extern DBCStorage <SpellEntry> sSpellStore; -extern DBCStorage <StableSlotPricesEntry> sStableSlotPricesStore; -extern DBCStorage <SummonPropertiesEntry> sSummonPropertiesStore; -extern DBCStorage <TalentEntry> sTalentStore; -extern DBCStorage <TalentTabEntry> sTalentTabStore; -extern DBCStorage <TaxiNodesEntry> sTaxiNodesStore; -extern DBCStorage <TaxiPathEntry> sTaxiPathStore; -extern TaxiMask sTaxiNodesMask; -extern TaxiMask sOldContinentsNodesMask; -extern TaxiMask sHordeTaxiNodesMask; -extern TaxiMask sAllianceTaxiNodesMask; -extern TaxiMask sDeathKnightTaxiNodesMask; -extern TaxiPathSetBySource sTaxiPathSetBySource; -extern TaxiPathNodesByPath sTaxiPathNodesByPath; -extern DBCStorage <TeamContributionPointsEntry> sTeamContributionPointsStore; -extern DBCStorage <TotemCategoryEntry> sTotemCategoryStore; -extern DBCStorage <VehicleEntry> sVehicleStore; -extern DBCStorage <VehicleSeatEntry> sVehicleSeatStore; -extern DBCStorage <WMOAreaTableEntry> sWMOAreaTableStore; -//extern DBCStorage <WorldMapAreaEntry> sWorldMapAreaStore; -- use Zone2MapCoordinates and Map2ZoneCoordinates -extern DBCStorage <WorldMapOverlayEntry> sWorldMapOverlayStore; -extern DBCStorage <WorldSafeLocsEntry> sWorldSafeLocsStore; - -void LoadDBCStores(const std::string& dataPath); +TC_GAME_API SkillRaceClassInfoEntry const* GetSkillRaceClassInfo(uint32 skill, uint8 race, uint8 class_); + +TC_GAME_API ResponseCodes ValidateName(std::wstring const& name, LocaleConstant locale); + +TC_GAME_API EmotesTextSoundEntry const* FindTextSoundEmoteFor(uint32 emote, uint32 race, uint32 gender); + +TC_GAME_API extern DBCStorage <AchievementEntry> sAchievementStore; +TC_GAME_API extern DBCStorage <AchievementCriteriaEntry> sAchievementCriteriaStore; +TC_GAME_API extern DBCStorage <AreaTableEntry> sAreaTableStore; +TC_GAME_API extern DBCStorage <AreaGroupEntry> sAreaGroupStore; +TC_GAME_API extern DBCStorage <AreaPOIEntry> sAreaPOIStore; +TC_GAME_API extern DBCStorage <AreaTriggerEntry> sAreaTriggerStore; +TC_GAME_API extern DBCStorage <AuctionHouseEntry> sAuctionHouseStore; +TC_GAME_API extern DBCStorage <BankBagSlotPricesEntry> sBankBagSlotPricesStore; +TC_GAME_API extern DBCStorage <BannedAddOnsEntry> sBannedAddOnsStore; +TC_GAME_API extern DBCStorage <BarberShopStyleEntry> sBarberShopStyleStore; +TC_GAME_API extern DBCStorage <BattlemasterListEntry> sBattlemasterListStore; +TC_GAME_API extern DBCStorage <ChatChannelsEntry> sChatChannelsStore; +TC_GAME_API extern DBCStorage <CharStartOutfitEntry> sCharStartOutfitStore; +TC_GAME_API extern DBCStorage <CharSectionsEntry> sCharSectionsStore; +TC_GAME_API extern DBCStorage <CharTitlesEntry> sCharTitlesStore; +TC_GAME_API extern DBCStorage <ChrClassesEntry> sChrClassesStore; +TC_GAME_API extern DBCStorage <ChrRacesEntry> sChrRacesStore; +TC_GAME_API extern DBCStorage <CinematicCameraEntry> sCinematicCameraStore; +TC_GAME_API extern DBCStorage <CinematicSequencesEntry> sCinematicSequencesStore; +TC_GAME_API extern DBCStorage <CreatureDisplayInfoEntry> sCreatureDisplayInfoStore; +TC_GAME_API extern DBCStorage <CreatureDisplayInfoExtraEntry> sCreatureDisplayInfoExtraStore; +TC_GAME_API extern DBCStorage <CreatureFamilyEntry> sCreatureFamilyStore; +TC_GAME_API extern DBCStorage <CreatureModelDataEntry> sCreatureModelDataStore; +TC_GAME_API extern DBCStorage <CreatureSpellDataEntry> sCreatureSpellDataStore; +TC_GAME_API extern DBCStorage <CreatureTypeEntry> sCreatureTypeStore; +TC_GAME_API extern DBCStorage <CurrencyTypesEntry> sCurrencyTypesStore; +TC_GAME_API extern DBCStorage <DestructibleModelDataEntry> sDestructibleModelDataStore; +TC_GAME_API extern DBCStorage <DungeonEncounterEntry> sDungeonEncounterStore; +TC_GAME_API extern DBCStorage <DurabilityCostsEntry> sDurabilityCostsStore; +TC_GAME_API extern DBCStorage <DurabilityQualityEntry> sDurabilityQualityStore; +TC_GAME_API extern DBCStorage <EmotesEntry> sEmotesStore; +TC_GAME_API extern DBCStorage <EmotesTextEntry> sEmotesTextStore; +TC_GAME_API extern DBCStorage <EmotesTextSoundEntry> sEmotesTextSoundStore; +TC_GAME_API extern DBCStorage <FactionEntry> sFactionStore; +TC_GAME_API extern DBCStorage <FactionTemplateEntry> sFactionTemplateStore; +TC_GAME_API extern DBCStorage <GameObjectDisplayInfoEntry> sGameObjectDisplayInfoStore; +TC_GAME_API extern DBCStorage <GemPropertiesEntry> sGemPropertiesStore; +TC_GAME_API extern DBCStorage <GlyphPropertiesEntry> sGlyphPropertiesStore; +TC_GAME_API extern DBCStorage <GlyphSlotEntry> sGlyphSlotStore; + +TC_GAME_API extern DBCStorage <GtBarberShopCostBaseEntry> sGtBarberShopCostBaseStore; +TC_GAME_API extern DBCStorage <GtCombatRatingsEntry> sGtCombatRatingsStore; +TC_GAME_API extern DBCStorage <GtChanceToMeleeCritBaseEntry> sGtChanceToMeleeCritBaseStore; +TC_GAME_API extern DBCStorage <GtChanceToMeleeCritEntry> sGtChanceToMeleeCritStore; +TC_GAME_API extern DBCStorage <GtChanceToSpellCritBaseEntry> sGtChanceToSpellCritBaseStore; +TC_GAME_API extern DBCStorage <GtChanceToSpellCritEntry> sGtChanceToSpellCritStore; +TC_GAME_API extern DBCStorage <GtNPCManaCostScalerEntry> sGtNPCManaCostScalerStore; +TC_GAME_API extern DBCStorage <GtOCTClassCombatRatingScalarEntry> sGtOCTClassCombatRatingScalarStore; +TC_GAME_API extern DBCStorage <GtOCTRegenHPEntry> sGtOCTRegenHPStore; +//TC_GAME_API extern DBCStorage <GtOCTRegenMPEntry> sGtOCTRegenMPStore; -- not used currently +TC_GAME_API extern DBCStorage <GtRegenHPPerSptEntry> sGtRegenHPPerSptStore; +TC_GAME_API extern DBCStorage <GtRegenMPPerSptEntry> sGtRegenMPPerSptStore; +TC_GAME_API extern DBCStorage <HolidaysEntry> sHolidaysStore; +TC_GAME_API extern DBCStorage <ItemEntry> sItemStore; +TC_GAME_API extern DBCStorage <ItemBagFamilyEntry> sItemBagFamilyStore; +//TC_GAME_API extern DBCStorage <ItemDisplayInfoEntry> sItemDisplayInfoStore; -- not used currently +TC_GAME_API extern DBCStorage <ItemExtendedCostEntry> sItemExtendedCostStore; +TC_GAME_API extern DBCStorage <ItemLimitCategoryEntry> sItemLimitCategoryStore; +TC_GAME_API extern DBCStorage <ItemRandomPropertiesEntry> sItemRandomPropertiesStore; +TC_GAME_API extern DBCStorage <ItemRandomSuffixEntry> sItemRandomSuffixStore; +TC_GAME_API extern DBCStorage <ItemSetEntry> sItemSetStore; +TC_GAME_API extern DBCStorage <LFGDungeonEntry> sLFGDungeonStore; +TC_GAME_API extern DBCStorage <LiquidTypeEntry> sLiquidTypeStore; +TC_GAME_API extern DBCStorage <LockEntry> sLockStore; +TC_GAME_API extern DBCStorage <MailTemplateEntry> sMailTemplateStore; +TC_GAME_API extern DBCStorage <MapEntry> sMapStore; +//TC_GAME_API extern DBCStorage <MapDifficultyEntry> sMapDifficultyStore; -- use GetMapDifficultyData insteed +TC_GAME_API extern MapDifficultyMap sMapDifficultyMap; +TC_GAME_API extern DBCStorage <MovieEntry> sMovieStore; +TC_GAME_API extern DBCStorage <OverrideSpellDataEntry> sOverrideSpellDataStore; +TC_GAME_API extern DBCStorage <PowerDisplayEntry> sPowerDisplayStore; +TC_GAME_API extern DBCStorage <QuestSortEntry> sQuestSortStore; +TC_GAME_API extern DBCStorage <QuestXPEntry> sQuestXPStore; +TC_GAME_API extern DBCStorage <QuestFactionRewEntry> sQuestFactionRewardStore; +TC_GAME_API extern DBCStorage <RandomPropertiesPointsEntry> sRandomPropertiesPointsStore; +TC_GAME_API extern DBCStorage <ScalingStatDistributionEntry> sScalingStatDistributionStore; +TC_GAME_API extern DBCStorage <ScalingStatValuesEntry> sScalingStatValuesStore; +TC_GAME_API extern DBCStorage <SkillLineEntry> sSkillLineStore; +TC_GAME_API extern DBCStorage <SkillLineAbilityEntry> sSkillLineAbilityStore; +TC_GAME_API extern DBCStorage <SkillTiersEntry> sSkillTiersStore; +TC_GAME_API extern DBCStorage <SoundEntriesEntry> sSoundEntriesStore; +TC_GAME_API extern DBCStorage <SpellCastTimesEntry> sSpellCastTimesStore; +TC_GAME_API extern DBCStorage <SpellCategoryEntry> sSpellCategoryStore; +TC_GAME_API extern DBCStorage <SpellDifficultyEntry> sSpellDifficultyStore; +TC_GAME_API extern DBCStorage <SpellDurationEntry> sSpellDurationStore; +TC_GAME_API extern DBCStorage <SpellFocusObjectEntry> sSpellFocusObjectStore; +TC_GAME_API extern DBCStorage <SpellItemEnchantmentEntry> sSpellItemEnchantmentStore; +TC_GAME_API extern DBCStorage <SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore; +TC_GAME_API extern PetFamilySpellsStore sPetFamilySpellsStore; +TC_GAME_API extern DBCStorage <SpellRadiusEntry> sSpellRadiusStore; +TC_GAME_API extern DBCStorage <SpellRangeEntry> sSpellRangeStore; +TC_GAME_API extern DBCStorage <SpellRuneCostEntry> sSpellRuneCostStore; +TC_GAME_API extern DBCStorage <SpellShapeshiftEntry> sSpellShapeshiftStore; +TC_GAME_API extern DBCStorage <SpellEntry> sSpellStore; +TC_GAME_API extern DBCStorage <StableSlotPricesEntry> sStableSlotPricesStore; +TC_GAME_API extern DBCStorage <SummonPropertiesEntry> sSummonPropertiesStore; +TC_GAME_API extern DBCStorage <TalentEntry> sTalentStore; +TC_GAME_API extern DBCStorage <TalentTabEntry> sTalentTabStore; +TC_GAME_API extern DBCStorage <TaxiNodesEntry> sTaxiNodesStore; +TC_GAME_API extern DBCStorage <TaxiPathEntry> sTaxiPathStore; +TC_GAME_API extern TaxiMask sTaxiNodesMask; +TC_GAME_API extern TaxiMask sOldContinentsNodesMask; +TC_GAME_API extern TaxiMask sHordeTaxiNodesMask; +TC_GAME_API extern TaxiMask sAllianceTaxiNodesMask; +TC_GAME_API extern TaxiMask sDeathKnightTaxiNodesMask; +TC_GAME_API extern TaxiPathSetBySource sTaxiPathSetBySource; +TC_GAME_API extern TaxiPathNodesByPath sTaxiPathNodesByPath; +TC_GAME_API extern DBCStorage <TeamContributionPointsEntry> sTeamContributionPointsStore; +TC_GAME_API extern DBCStorage <TotemCategoryEntry> sTotemCategoryStore; +TC_GAME_API extern DBCStorage <VehicleEntry> sVehicleStore; +TC_GAME_API extern DBCStorage <VehicleSeatEntry> sVehicleSeatStore; +TC_GAME_API extern DBCStorage <WMOAreaTableEntry> sWMOAreaTableStore; +//TC_GAME_API extern DBCStorage <WorldMapAreaEntry> sWorldMapAreaStore; -- use Zone2MapCoordinates and Map2ZoneCoordinates +TC_GAME_API extern DBCStorage <WorldMapOverlayEntry> sWorldMapOverlayStore; +TC_GAME_API extern DBCStorage <WorldSafeLocsEntry> sWorldSafeLocsStore; + +TC_GAME_API void LoadDBCStores(const std::string& dataPath); #endif diff --git a/src/server/game/DataStores/DBCStructure.h b/src/server/game/DataStores/DBCStructure.h index b5dc4489148..13f0198a5e7 100644 --- a/src/server/game/DataStores/DBCStructure.h +++ b/src/server/game/DataStores/DBCStructure.h @@ -725,24 +725,20 @@ struct ChrRacesEntry uint32 expansion; // 68 (0 - original race, 1 - tbc addon, ...) }; -/* not used struct CinematicCameraEntry { - uint32 id; // 0 index - char* filename; // 1 - uint32 soundid; // 2 in SoundEntries.dbc or 0 - float start_x; // 3 - float start_y; // 4 - float start_z; // 5 - float unk6; // 6 speed? + uint32 ID; // 0 + char const* Model; // 1 Model filename (translate .mdx to .m2) + uint32 SoundID; // 2 Sound ID (voiceover for cinematic) + DBCPosition3D Origin; // 3-5 Position in map used for basis for M2 co-ordinates + float OriginFacing; // 6 Orientation in map used for basis for M2 co-ordinates }; -*/ struct CinematicSequencesEntry { uint32 Id; // 0 index //uint32 unk1; // 1 always 0 - //uint32 cinematicCamera; // 2 id in CinematicCamera.dbc + uint32 cinematicCamera; // 2 id in CinematicCamera.dbc // 3-9 always 0 }; diff --git a/src/server/game/DataStores/DBCfmt.h b/src/server/game/DataStores/DBCfmt.h index c61ec997bc2..1accc81714b 100644 --- a/src/server/game/DataStores/DBCfmt.h +++ b/src/server/game/DataStores/DBCfmt.h @@ -38,7 +38,8 @@ char const CharTitlesEntryfmt[] = "nxssssssssssssssssxssssssssssssssssxi"; char const ChatChannelsEntryfmt[] = "nixssssssssssssssssxxxxxxxxxxxxxxxxxx"; char const ChrClassesEntryfmt[] = "nxixssssssssssssssssxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxixii"; char const ChrRacesEntryfmt[] = "niixiixixxxxixssssssssssssssssxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxi"; -char const CinematicSequencesEntryfmt[] = "nxxxxxxxxx"; +char const CinematicCameraEntryfmt[] = "nsiffff"; +char const CinematicSequencesEntryfmt[] = "nxixxxxxxx"; char const CreatureDisplayInfofmt[] = "nixifxxxxxxxxxxx"; char const CreatureDisplayInfoExtrafmt[] = "diixxxxxxxxxxxxxxxxxx"; char const CreatureFamilyfmt[] = "nfifiiiiixssssssssssssssssxx"; diff --git a/src/server/game/DataStores/M2Stores.cpp b/src/server/game/DataStores/M2Stores.cpp new file mode 100644 index 00000000000..69581f16549 --- /dev/null +++ b/src/server/game/DataStores/M2Stores.cpp @@ -0,0 +1,266 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "DBCStores.h" +#include "M2Structure.h" +#include "M2Stores.h" +#include "Common.h" +#include "Containers.h" +#include "Log.h" +#include "World.h" +#include <fstream> +#include <iostream> +#include <iomanip> +#include <boost/filesystem/path.hpp> + +std::unordered_map<uint32, FlyByCameraCollection> sFlyByCameraStore; + +// Convert the geomoetry from a spline value, to an actual WoW XYZ +G3D::Vector3 TranslateLocation(G3D::Vector4 const* DBCPosition, G3D::Vector3 const* basePosition, G3D::Vector3 const* splineVector) +{ + G3D::Vector3 work; + float x = basePosition->x + splineVector->x; + float y = basePosition->y + splineVector->y; + float z = basePosition->z + splineVector->z; + float const distance = sqrt((x * x) + (y * y)); + float angle = std::atan2(x, y) - DBCPosition->w; + + if (angle < 0) + angle += 2 * float(M_PI); + + work.x = DBCPosition->x + (distance * sin(angle)); + work.y = DBCPosition->y + (distance * cos(angle)); + work.z = DBCPosition->z + z; + return work; +} + +// Number of cameras not used. Multiple cameras never used in 3.3.5 +bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, CinematicCameraEntry const* dbcentry) +{ + char const* buffer = reinterpret_cast<char const*>(header); + + FlyByCameraCollection cameras; + FlyByCameraCollection targetcam; + + G3D::Vector4 DBCData; + DBCData.x = dbcentry->Origin.X; + DBCData.y = dbcentry->Origin.Y; + DBCData.z = dbcentry->Origin.Z; + DBCData.w = dbcentry->OriginFacing; + + // Read target locations, only so that we can calculate orientation + for (uint32 k = 0; k < cam->target_positions.timestamps.number; ++k) + { + // Extract Target positions + if (cam->target_positions.timestamps.offset_elements + sizeof(M2Array) > buffSize) + return false; + M2Array const* targTsArray = reinterpret_cast<M2Array const*>(buffer + cam->target_positions.timestamps.offset_elements); + if (targTsArray->offset_elements + sizeof(uint32) > buffSize || cam->target_positions.values.offset_elements + sizeof(M2Array) > buffSize) + return false; + uint32 const* targTimestamps = reinterpret_cast<uint32 const*>(buffer + targTsArray->offset_elements); + M2Array const* targArray = reinterpret_cast<M2Array const*>(buffer + cam->target_positions.values.offset_elements); + + if (targArray->offset_elements + sizeof(M2SplineKey<G3D::Vector3>) > buffSize) + return false; + M2SplineKey<G3D::Vector3> const* targPositions = reinterpret_cast<M2SplineKey<G3D::Vector3> const*>(buffer + targArray->offset_elements); + + // Read the data for this set + uint32 currPos = targArray->offset_elements; + for (uint32 i = 0; i < targTsArray->number; ++i) + { + if (currPos + sizeof(M2SplineKey<G3D::Vector3>) > buffSize) + return false; + // Translate co-ordinates + G3D::Vector3 newPos = TranslateLocation(&DBCData, &cam->target_position_base, &targPositions->p0); + + // Add to vector + FlyByCamera thisCam; + thisCam.timeStamp = targTimestamps[i]; + thisCam.locations.x = newPos.x; + thisCam.locations.y = newPos.y; + thisCam.locations.z = newPos.z; + thisCam.locations.w = 0.0f; + targetcam.push_back(thisCam); + targPositions++; + currPos += sizeof(M2SplineKey<G3D::Vector3>); + } + } + + // Read camera positions and timestamps (translating first position of 3 only, we don't need to translate the whole spline) + for (uint32 k = 0; k < cam->positions.timestamps.number; ++k) + { + // Extract Camera positions for this set + if (cam->positions.timestamps.offset_elements + sizeof(M2Array) > buffSize) + return false; + M2Array const* posTsArray = reinterpret_cast<M2Array const*>(buffer + cam->positions.timestamps.offset_elements); + if (posTsArray->offset_elements + sizeof(uint32) > buffSize || cam->positions.values.offset_elements + sizeof(M2Array) > buffSize) + return false; + uint32 const* posTimestamps = reinterpret_cast<uint32 const*>(buffer + posTsArray->offset_elements); + M2Array const* posArray = reinterpret_cast<M2Array const*>(buffer + cam->positions.values.offset_elements); + if (posArray->offset_elements + sizeof(M2SplineKey<G3D::Vector3>) > buffSize) + return false; + M2SplineKey<G3D::Vector3> const* positions = reinterpret_cast<M2SplineKey<G3D::Vector3> const*>(buffer + posArray->offset_elements); + + // Read the data for this set + uint32 currPos = posArray->offset_elements; + for (uint32 i = 0; i < posTsArray->number; ++i) + { + if (currPos + sizeof(M2SplineKey<G3D::Vector3>) > buffSize) + return false; + // Translate co-ordinates + G3D::Vector3 newPos = TranslateLocation(&DBCData, &cam->position_base, &positions->p0); + + // Add to vector + FlyByCamera thisCam; + thisCam.timeStamp = posTimestamps[i]; + thisCam.locations.x = newPos.x; + thisCam.locations.y = newPos.y; + thisCam.locations.z = newPos.z; + + if (targetcam.size() > 0) + { + // Find the target camera before and after this camera + FlyByCamera lastTarget; + FlyByCamera nextTarget; + + // Pre-load first item + lastTarget = targetcam[0]; + nextTarget = targetcam[0]; + for (uint32 j = 0; j < targetcam.size(); ++j) + { + nextTarget = targetcam[j]; + if (targetcam[j].timeStamp > posTimestamps[i]) + break; + + lastTarget = targetcam[j]; + } + + float x = lastTarget.locations.x; + float y = lastTarget.locations.y; + float z = lastTarget.locations.z; + + // Now, the timestamps for target cam and position can be different. So, if they differ we interpolate + if (lastTarget.timeStamp != posTimestamps[i]) + { + uint32 timeDiffTarget = nextTarget.timeStamp - lastTarget.timeStamp; + uint32 timeDiffThis = posTimestamps[i] - lastTarget.timeStamp; + float xDiff = nextTarget.locations.x - lastTarget.locations.x; + float yDiff = nextTarget.locations.y - lastTarget.locations.y; + float zDiff = nextTarget.locations.z - lastTarget.locations.z; + x = lastTarget.locations.x + (xDiff * (float(timeDiffThis) / float(timeDiffTarget))); + y = lastTarget.locations.y + (yDiff * (float(timeDiffThis) / float(timeDiffTarget))); + z = lastTarget.locations.z + (zDiff * (float(timeDiffThis) / float(timeDiffTarget))); + } + float xDiff = x - thisCam.locations.x; + float yDiff = y - thisCam.locations.y; + thisCam.locations.w = std::atan2(yDiff, xDiff); + + if (thisCam.locations.w < 0) + thisCam.locations.w += 2 * float(M_PI); + } + + cameras.push_back(thisCam); + positions++; + currPos += sizeof(M2SplineKey<G3D::Vector3>); + } + } + + sFlyByCameraStore[dbcentry->ID] = cameras; + return true; +} + +void LoadM2Cameras(std::string const& dataPath) +{ + sFlyByCameraStore.clear(); + TC_LOG_INFO("server.loading", ">> Loading Cinematic Camera files"); + + uint32 oldMSTime = getMSTime(); + for (uint32 i = 0; i < sCinematicCameraStore.GetNumRows(); ++i) + { + if (CinematicCameraEntry const* dbcentry = sCinematicCameraStore.LookupEntry(i)) + { + std::string filenameWork = dataPath; + filenameWork.append(dbcentry->Model); + + // Replace slashes (always to forward slash, because boost!) + std::replace(filenameWork.begin(), filenameWork.end(), '\\', '/'); + + boost::filesystem::path filename = filenameWork; + + // Convert to native format + filename.make_preferred(); + + // Replace mdx to .m2 + filename.replace_extension("m2"); + + std::ifstream m2file(filename.string().c_str(), std::ios::in | std::ios::binary); + if (!m2file.is_open()) + continue; + + // Get file size + m2file.seekg(0, std::ios::end); + std::streamoff const fileSize = m2file.tellg(); + + // Reject if not at least the size of the header + if (static_cast<uint32 const>(fileSize) < sizeof(M2Header)) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File is smaller than header size", filename.string().c_str()); + m2file.close(); + continue; + } + + // Read 4 bytes (signature) + m2file.seekg(0, std::ios::beg); + char fileCheck[5]; + m2file.read(fileCheck, 4); + fileCheck[4] = 0; + + // Check file has correct magic (MD20) + if (strcmp(fileCheck, "MD20")) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File identifier not found", filename.string().c_str()); + m2file.close(); + continue; + } + + // Now we have a good file, read it all into a vector of char's, then close the file. + std::vector<char> buffer(fileSize); + m2file.seekg(0, std::ios::beg); + if (!m2file.read(buffer.data(), fileSize)) + { + m2file.close(); + continue; + } + m2file.close(); + + // Read header + M2Header const* header = reinterpret_cast<M2Header const*>(buffer.data()); + + if (header->ofsCameras + sizeof(M2Camera) > static_cast<uint32 const>(fileSize)) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); + continue; + } + + // Get camera(s) - Main header, then dump them. + M2Camera const* cam = reinterpret_cast<M2Camera const*>(buffer.data() + header->ofsCameras); + if (!readCamera(cam, fileSize, header, dbcentry)) + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); + } + } + TC_LOG_INFO("server.loading", ">> Loaded %u cinematic waypoint sets in %u ms", (uint32)sFlyByCameraStore.size(), GetMSTimeDiffToNow(oldMSTime)); +} diff --git a/src/server/game/DataStores/M2Stores.h b/src/server/game/DataStores/M2Stores.h new file mode 100644 index 00000000000..97224475e5d --- /dev/null +++ b/src/server/game/DataStores/M2Stores.h @@ -0,0 +1,36 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef TRINITY_M2STORES_H +#define TRINITY_M2STORES_H + +#include "SharedDefines.h" +#include "Common.h" + +struct FlyByCamera +{ + uint32 timeStamp; + G3D::Vector4 locations; +}; + +typedef std::vector<FlyByCamera> FlyByCameraCollection; + +TC_GAME_API extern std::unordered_map<uint32, FlyByCameraCollection> sFlyByCameraStore; + +TC_GAME_API void LoadM2Cameras(std::string const& dataPath); + +#endif
\ No newline at end of file diff --git a/src/server/game/DataStores/M2Structure.h b/src/server/game/DataStores/M2Structure.h new file mode 100644 index 00000000000..43e8d008b9f --- /dev/null +++ b/src/server/game/DataStores/M2Structure.h @@ -0,0 +1,133 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef TRINITY_M2STRUCTURE_H +#define TRINITY_M2STRUCTURE_H + +#include <G3D/Vector3.h> +#include <G3D/AABox.h> + +// Structures for M2 file. Source: https://wowdev.wiki +#pragma pack(push, 1) +template<typename T> +struct M2SplineKey +{ + T p0; + T p1; + T p2; +}; + +struct M2Header +{ + char Magic[4]; // "MD20" + uint32 Version; // The version of the format. + uint32 lName; // Length of the model's name including the trailing \0 + uint32 ofsName; // Offset to the name, it seems like models can get reloaded by this name.should be unique, i guess. + uint32 GlobalModelFlags; // 0x0001: tilt x, 0x0002: tilt y, 0x0008: add 2 fields in header, 0x0020: load .phys data (MoP+), 0x0080: has _lod .skin files (MoP?+), 0x0100: is camera related. + uint32 nGlobalSequences; + uint32 ofsGlobalSequences; // A list of timestamps. + uint32 nAnimations; + uint32 ofsAnimations; // Information about the animations in the model. + uint32 nAnimationLookup; + uint32 ofsAnimationLookup; // Mapping of global IDs to the entries in the Animation sequences block. + uint32 nBones; // MAX_BONES = 0x100 + uint32 ofsBones; // Information about the bones in this model. + uint32 nKeyBoneLookup; + uint32 ofsKeyBoneLookup; // Lookup table for key skeletal bones. + uint32 nVertices; + uint32 ofsVertices; // Vertices of the model. + uint32 nViews; // Views (LOD) are now in .skins. + uint32 nSubmeshAnimations; + uint32 ofsSubmeshAnimations; // Submesh color and alpha animations definitions. + uint32 nTextures; + uint32 ofsTextures; // Textures of this model. + uint32 nTransparency; + uint32 ofsTransparency; // Transparency of textures. + uint32 nUVAnimation; + uint32 ofsUVAnimation; + uint32 nTexReplace; + uint32 ofsTexReplace; // Replaceable Textures. + uint32 nRenderFlags; + uint32 ofsRenderFlags; // Blending modes / render flags. + uint32 nBoneLookupTable; + uint32 ofsBoneLookupTable; // A bone lookup table. + uint32 nTexLookup; + uint32 ofsTexLookup; // The same for textures. + uint32 nTexUnits; // possibly removed with cata?! + uint32 ofsTexUnits; // And texture units. Somewhere they have to be too. + uint32 nTransLookup; + uint32 ofsTransLookup; // Everything needs its lookup. Here are the transparencies. + uint32 nUVAnimLookup; + uint32 ofsUVAnimLookup; + G3D::AABox BoundingBox; // min/max( [1].z, 2.0277779f ) - 0.16f seems to be the maximum camera height + float BoundingSphereRadius; + G3D::AABox CollisionBox; + float CollisionSphereRadius; + uint32 nBoundingTriangles; + uint32 ofsBoundingTriangles; // Our bounding volumes. Similar structure like in the old ofsViews. + uint32 nBoundingVertices; + uint32 ofsBoundingVertices; + uint32 nBoundingNormals; + uint32 ofsBoundingNormals; + uint32 nAttachments; + uint32 ofsAttachments; // Attachments are for weapons etc. + uint32 nAttachLookup; + uint32 ofsAttachLookup; // Of course with a lookup. + uint32 nEvents; + uint32 ofsEvents; // Used for playing sounds when dying and a lot else. + uint32 nLights; + uint32 ofsLights; // Lights are mainly used in loginscreens but in wands and some doodads too. + uint32 nCameras; // Format of Cameras changed with version 271! + uint32 ofsCameras; // The cameras are present in most models for having a model in the Character-Tab. + uint32 nCameraLookup; + uint32 ofsCameraLookup; // And lookup-time again. + uint32 nRibbonEmitters; + uint32 ofsRibbonEmitters; // Things swirling around. See the CoT-entrance for light-trails. + uint32 nParticleEmitters; + uint32 ofsParticleEmitters; // Spells and weapons, doodads and loginscreens use them. Blood dripping of a blade? Particles. + uint32 nBlendMaps; // This has to deal with blending. Exists IFF (flags & 0x8) != 0. When set, textures blending is overriden by the associated array. See M2/WotLK#Blend_mode_overrides + uint32 ofsBlendMaps; // Same as above. Points to an array of uint16 of nBlendMaps entries -- From WoD information.}; +}; + +struct M2Array +{ + uint32_t number; + uint32 offset_elements; +}; +struct M2Track +{ + uint16_t interpolation_type; + uint16_t global_sequence; + M2Array timestamps; + M2Array values; +}; + +struct M2Camera +{ + uint32_t type; // 0: portrait, 1: characterinfo; -1: else (flyby etc.); referenced backwards in the lookup table. + float fov; // No radians, no degrees. Multiply by 35 to get degrees. + float far_clip; + float near_clip; + M2Track positions; // How the camera's position moves. Should be 3*3 floats. + G3D::Vector3 position_base; + M2Track target_positions; // How the target moves. Should be 3*3 floats. + G3D::Vector3 target_position_base; + M2Track rolldata; // The camera can have some roll-effect. Its 0 to 2*Pi. +}; +#pragma pack(pop) + +#endif
\ No newline at end of file diff --git a/src/server/game/DungeonFinding/LFG.h b/src/server/game/DungeonFinding/LFG.h index 73c123723b1..b837a0df272 100644 --- a/src/server/game/DungeonFinding/LFG.h +++ b/src/server/game/DungeonFinding/LFG.h @@ -101,9 +101,9 @@ typedef std::map<ObjectGuid, LfgLockMap> LfgLockPartyMap; typedef std::map<ObjectGuid, uint8> LfgRolesMap; typedef std::map<ObjectGuid, ObjectGuid> LfgGroupsMap; -std::string ConcatenateDungeons(LfgDungeonSet const& dungeons); -std::string GetRolesString(uint8 roles); -std::string GetStateString(LfgState state); +TC_GAME_API std::string ConcatenateDungeons(LfgDungeonSet const& dungeons); +TC_GAME_API std::string GetRolesString(uint8 roles); +TC_GAME_API std::string GetStateString(LfgState state); } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGGroupData.h b/src/server/game/DungeonFinding/LFGGroupData.h index 7ae4777cd4d..62a41b6b350 100644 --- a/src/server/game/DungeonFinding/LFGGroupData.h +++ b/src/server/game/DungeonFinding/LFGGroupData.h @@ -31,7 +31,7 @@ enum LfgGroupEnum /** Stores all lfg data needed about a group. */ -class LfgGroupData +class TC_GAME_API LfgGroupData { public: LfgGroupData(); diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index b0a1777f19a..4ca1a68c048 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -40,8 +40,6 @@ namespace lfg LFGMgr::LFGMgr(): m_QueueTimer(0), m_lfgProposalId(1), m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK)) { - new LFGPlayerScript(); - new LFGGroupScript(); } LFGMgr::~LFGMgr() @@ -84,19 +82,19 @@ void LFGMgr::_SaveToDB(ObjectGuid guid, uint32 db_guid) if (!guid.IsGroup()) return; - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_LFG_DATA); + SQLTransaction trans = CharacterDatabase.BeginTransaction(); + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_LFG_DATA); stmt->setUInt32(0, db_guid); - - CharacterDatabase.Execute(stmt); + trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_LFG_DATA); stmt->setUInt32(0, db_guid); - stmt->setUInt32(1, GetDungeon(guid)); stmt->setUInt32(2, GetState(guid)); + trans->Append(stmt); - CharacterDatabase.Execute(stmt); + CharacterDatabase.CommitTransaction(trans); } /// Load rewards for completing dungeons @@ -261,6 +259,12 @@ void LFGMgr::LoadLFGDungeons(bool reload /* = false */) } } +LFGMgr* LFGMgr::instance() +{ + static LFGMgr instance; + return &instance; +} + void LFGMgr::Update(uint32 diff) { if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) @@ -1142,7 +1146,7 @@ void LFGMgr::RemoveProposal(LfgProposalContainer::iterator itProposal, LfgUpdate for (GuidList::const_iterator it = proposal.queues.begin(); it != proposal.queues.end(); ++it) { ObjectGuid guid = *it; - queue.AddToQueue(guid); + queue.AddToQueue(guid, true); } ProposalsStore.erase(itProposal); @@ -1900,8 +1904,16 @@ bool LFGMgr::AllQueued(GuidList const& check) return false; for (GuidList::const_iterator it = check.begin(); it != check.end(); ++it) - if (GetState(*it) != LFG_STATE_QUEUED) + { + LfgState state = GetState(*it); + if (state != LFG_STATE_QUEUED) + { + if (state != LFG_STATE_PROPOSAL) + TC_LOG_DEBUG("lfg.allqueued", "Unexpected state found while trying to form new group. Guid: %s, State: %s", (*it).ToString().c_str(), GetStateString(state).c_str()); + return false; + } + } return true; } diff --git a/src/server/game/DungeonFinding/LFGMgr.h b/src/server/game/DungeonFinding/LFGMgr.h index 90a8d802f9d..c72c0a3cdab 100644 --- a/src/server/game/DungeonFinding/LFGMgr.h +++ b/src/server/game/DungeonFinding/LFGMgr.h @@ -289,18 +289,14 @@ struct LFGDungeonData uint32 Entry() const { return id + (type << 24); } }; -class LFGMgr +class TC_GAME_API LFGMgr { private: LFGMgr(); ~LFGMgr(); public: - static LFGMgr* instance() - { - static LFGMgr instance; - return &instance; - } + static LFGMgr* instance(); // Functions used outside lfg namespace void Update(uint32 diff); diff --git a/src/server/game/DungeonFinding/LFGPlayerData.h b/src/server/game/DungeonFinding/LFGPlayerData.h index 859317ca956..91e4153a6d5 100644 --- a/src/server/game/DungeonFinding/LFGPlayerData.h +++ b/src/server/game/DungeonFinding/LFGPlayerData.h @@ -26,7 +26,7 @@ namespace lfg /** Stores all lfg data needed about the player. */ -class LfgPlayerData +class TC_GAME_API LfgPlayerData { public: LfgPlayerData(); diff --git a/src/server/game/DungeonFinding/LFGQueue.cpp b/src/server/game/DungeonFinding/LFGQueue.cpp index 314803d1602..d156158dee6 100644 --- a/src/server/game/DungeonFinding/LFGQueue.cpp +++ b/src/server/game/DungeonFinding/LFGQueue.cpp @@ -117,7 +117,7 @@ std::string LFGQueue::GetDetailedMatchRoles(GuidList const& check) const return o.str(); } -void LFGQueue::AddToQueue(ObjectGuid guid) +void LFGQueue::AddToQueue(ObjectGuid guid, bool reAdd) { LfgQueueDataContainer::iterator itQueue = QueueDataStore.find(guid); if (itQueue == QueueDataStore.end()) @@ -126,7 +126,10 @@ void LFGQueue::AddToQueue(ObjectGuid guid) return; } - AddToNewQueue(guid); + if (reAdd) + AddToFrontCurrentQueue(guid); + else + AddToNewQueue(guid); } void LFGQueue::RemoveFromQueue(ObjectGuid guid) @@ -171,6 +174,11 @@ void LFGQueue::AddToCurrentQueue(ObjectGuid guid) currentQueueStore.push_back(guid); } +void LFGQueue::AddToFrontCurrentQueue(ObjectGuid guid) +{ + currentQueueStore.push_front(guid); +} + void LFGQueue::RemoveFromCurrentQueue(ObjectGuid guid) { currentQueueStore.remove(guid); diff --git a/src/server/game/DungeonFinding/LFGQueue.h b/src/server/game/DungeonFinding/LFGQueue.h index ed8193ab605..32711e81468 100644 --- a/src/server/game/DungeonFinding/LFGQueue.h +++ b/src/server/game/DungeonFinding/LFGQueue.h @@ -83,13 +83,13 @@ typedef std::map<ObjectGuid, LfgQueueData> LfgQueueDataContainer; /** Stores all data related to queue */ -class LFGQueue +class TC_GAME_API LFGQueue { public: // Add/Remove from queue std::string GetDetailedMatchRoles(GuidList const& check) const; - void AddToQueue(ObjectGuid guid); + void AddToQueue(ObjectGuid guid, bool reAdd = false); void RemoveFromQueue(ObjectGuid guid); void AddQueueData(ObjectGuid guid, time_t joinTime, LfgDungeonSet const& dungeons, LfgRolesMap const& rolesMap); void RemoveQueueData(ObjectGuid guid); @@ -116,6 +116,7 @@ class LFGQueue void AddToNewQueue(ObjectGuid guid); void AddToCurrentQueue(ObjectGuid guid); + void AddToFrontCurrentQueue(ObjectGuid guid); void RemoveFromNewQueue(ObjectGuid guid); void RemoveFromCurrentQueue(ObjectGuid guid); diff --git a/src/server/game/DungeonFinding/LFGScripts.cpp b/src/server/game/DungeonFinding/LFGScripts.cpp index 79d36055870..1d2b963b254 100644 --- a/src/server/game/DungeonFinding/LFGScripts.cpp +++ b/src/server/game/DungeonFinding/LFGScripts.cpp @@ -241,4 +241,10 @@ void LFGGroupScript::OnInviteMember(Group* group, ObjectGuid guid) sLFGMgr->LeaveLfg(leader); } +void AddSC_LFGScripts() +{ + new LFGPlayerScript(); + new LFGGroupScript(); +} + } // namespace lfg diff --git a/src/server/game/DungeonFinding/LFGScripts.h b/src/server/game/DungeonFinding/LFGScripts.h index 377614bc55d..9f52668ea61 100644 --- a/src/server/game/DungeonFinding/LFGScripts.h +++ b/src/server/game/DungeonFinding/LFGScripts.h @@ -29,7 +29,7 @@ class Group; namespace lfg { -class LFGPlayerScript : public PlayerScript +class TC_GAME_API LFGPlayerScript : public PlayerScript { public: LFGPlayerScript(); @@ -40,7 +40,7 @@ class LFGPlayerScript : public PlayerScript void OnMapChanged(Player* player) override; }; -class LFGGroupScript : public GroupScript +class TC_GAME_API LFGGroupScript : public GroupScript { public: LFGGroupScript(); @@ -53,4 +53,6 @@ class LFGGroupScript : public GroupScript void OnInviteMember(Group* group, ObjectGuid guid) override; }; +/*keep private*/ void AddSC_LFGScripts(); + } // namespace lfg diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index 8f700cc636f..22bb9bca712 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -147,7 +147,7 @@ bool Corpse::LoadCorpseFromDB(ObjectGuid::LowType guid, Field* fields) SetObjectScale(1.0f); SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, fields[5].GetUInt32()); - _LoadIntoDataField(fields[6].GetCString(), CORPSE_FIELD_ITEM, EQUIPMENT_SLOT_END); + _LoadIntoDataField(fields[6].GetString(), CORPSE_FIELD_ITEM, EQUIPMENT_SLOT_END); SetUInt32Value(CORPSE_FIELD_BYTES_1, fields[7].GetUInt32()); SetUInt32Value(CORPSE_FIELD_BYTES_2, fields[8].GetUInt32()); SetUInt32Value(CORPSE_FIELD_GUILD, fields[9].GetUInt32()); diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 5062645eac8..c9dd0b01509 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -46,7 +46,7 @@ enum CorpseFlags CORPSE_FLAG_LOOTABLE = 0x20 }; -class Corpse : public WorldObject, public GridObject<Corpse> +class TC_GAME_API Corpse : public WorldObject, public GridObject<Corpse> { public: explicit Corpse(CorpseType type = CORPSE_BONES); diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 5d62b740947..4a5f70165fc 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -54,7 +54,7 @@ TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const if (itr != spellList.end()) return &itr->second; - return NULL; + return nullptr; } bool VendorItemData::RemoveItem(uint32 item_id) @@ -78,7 +78,7 @@ VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, uint32 extend for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i) if ((*i)->item == item_id && (*i)->ExtendedCost == extendedCost) return *i; - return NULL; + return nullptr; } uint32 CreatureTemplate::GetRandomValidModelId() const @@ -182,13 +182,13 @@ m_groupLootTimer(0), lootingGroupLowGUID(0), m_PlayerDamageReq(0), m_lootRecipient(), m_lootRecipientGroup(0), _skinner(), _pickpocketLootRestore(0), m_corpseRemoveTime(0), m_respawnTime(0), m_respawnDelay(300), m_corpseDelay(60), m_respawnradius(0.0f), m_boundaryCheckTime(2500), m_combatPulseTime(0), m_combatPulseDelay(0), m_reactState(REACT_AGGRESSIVE), m_defaultMovementType(IDLE_MOTION_TYPE), m_spawnId(0), m_equipmentId(0), m_originalEquipmentId(0), m_AlreadyCallAssistance(false), -m_AlreadySearchedAssistance(false), m_regenHealth(true), m_AI_locked(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL), -m_originalEntry(0), m_homePosition(), m_transportHomePosition(), m_creatureInfo(NULL), m_creatureData(NULL), m_waypointID(0), m_path_id(0), m_formation(NULL) +m_AlreadySearchedAssistance(false), m_regenHealth(true), m_cannotReachTarget(false), m_cannotReachTimer(0), m_AI_locked(false), m_meleeDamageSchoolMask(SPELL_SCHOOL_MASK_NORMAL), +m_originalEntry(0), m_homePosition(), m_transportHomePosition(), m_creatureInfo(nullptr), m_creatureData(nullptr), m_waypointID(0), m_path_id(0), m_formation(nullptr), m_focusSpell(nullptr), m_focusDelay(0) { m_regenTimer = CREATURE_REGEN_INTERVAL; m_valuesCount = UNIT_END; - for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i = 0; i < MAX_CREATURE_SPELLS; ++i) m_spells[i] = 0; DisableReputationGain = false; @@ -197,16 +197,14 @@ m_originalEntry(0), m_homePosition(), m_transportHomePosition(), m_creatureInfo( m_CombatDistance = 0;//MELEE_RANGE; ResetLootMode(); // restore default loot mode - TriggerJustRespawned = false; + m_TriggerJustRespawned = false; m_isTempWorldObject = false; - _focusSpell = NULL; - _focusDelay = 0; } Creature::~Creature() { delete i_AI; - i_AI = NULL; + i_AI = nullptr; //if (m_uint32Values) // TC_LOG_ERROR("entities.unit", "Deconstruct Creature Entry = %u", GetEntry()); @@ -344,10 +342,10 @@ bool Creature::InitEntry(uint32 entry, CreatureData const* data /*= nullptr*/) m_creatureInfo = cinfo; // map mode related always // equal to player Race field, but creature does not have race - SetByteValue(UNIT_FIELD_BYTES_0, 0, 0); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_RACE, 0); // known valid are: CLASS_WARRIOR, CLASS_PALADIN, CLASS_ROGUE, CLASS_MAGE - SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class)); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, uint8(cinfo->unit_class)); // Cancel load if no model defined if (!(cinfo->GetFirstValidModelId())) @@ -366,25 +364,25 @@ bool Creature::InitEntry(uint32 entry, CreatureData const* data /*= nullptr*/) SetDisplayId(displayID); SetNativeDisplayId(displayID); - SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, minfo->gender); // Load creature equipment - if (data && data->equipmentId != 0) + if (!data || data->equipmentId == 0) + LoadEquipment(); // use default equipment (if available) + else if (data && data->equipmentId != 0) // override, 0 means no equipment { m_originalEquipmentId = data->equipmentId; LoadEquipment(data->equipmentId); } - else - LoadEquipment(0, true); SetName(normalInfo->Name); // at normal entry always SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); - SetSpeed(MOVE_WALK, cinfo->speed_walk); - SetSpeed(MOVE_RUN, cinfo->speed_run); - SetSpeed(MOVE_SWIM, 1.0f); // using 1.0 rate - SetSpeed(MOVE_FLIGHT, 1.0f); // using 1.0 rate + SetSpeedRate(MOVE_WALK, cinfo->speed_walk); + SetSpeedRate(MOVE_RUN, cinfo->speed_run); + SetSpeedRate(MOVE_SWIM, 1.0f); // using 1.0 rate + SetSpeedRate(MOVE_FLIGHT, 1.0f); // using 1.0 rate // Will set UNIT_FIELD_BOUNDINGRADIUS and UNIT_FIELD_COMBATREACH SetObjectScale(cinfo->scale); @@ -396,7 +394,7 @@ bool Creature::InitEntry(uint32 entry, CreatureData const* data /*= nullptr*/) if (!m_respawnradius && m_defaultMovementType == RANDOM_MOTION_TYPE) m_defaultMovementType = IDLE_MOTION_TYPE; - for (uint8 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i=0; i < MAX_CREATURE_SPELLS; ++i) m_spells[i] = GetCreatureTemplate()->spells[i]; return true; @@ -483,6 +481,9 @@ bool Creature::UpdateEntry(uint32 entry, CreatureData const* data /*= nullptr*/) ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true); } + if (cInfo->InhabitType & INHABIT_ROOT) + SetControlled(true, UNIT_STATE_ROOT); + UpdateMovementFlags(); LoadCreaturesAddon(); return true; @@ -490,9 +491,9 @@ bool Creature::UpdateEntry(uint32 entry, CreatureData const* data /*= nullptr*/) void Creature::Update(uint32 diff) { - if (IsAIEnabled && TriggerJustRespawned) + if (IsAIEnabled && m_TriggerJustRespawned) { - TriggerJustRespawned = false; + m_TriggerJustRespawned = false; AI()->JustRespawned(); if (m_vehicleKit) m_vehicleKit->Reset(); @@ -578,7 +579,8 @@ void Creature::Update(uint32 diff) IsAIEnabled = true; if (!IsInEvadeMode() && LastCharmerGUID) if (Unit* charmer = ObjectAccessor::GetUnit(*this, LastCharmerGUID)) - i_AI->AttackStart(charmer); + if (CanStartAttack(charmer, true)) + i_AI->AttackStart(charmer); LastCharmerGUID.Clear(); } @@ -649,33 +651,32 @@ void Creature::Update(uint32 diff) m_regenTimer -= diff; } - if (m_regenTimer != 0) - break; - - bool bInCombat = IsInCombat() && (!GetVictim() || // if IsInCombat() is true and this has no victim - !EnsureVictim()->GetCharmerOrOwnerPlayerOrPlayerItself() || // or the victim/owner/charmer is not a player - !EnsureVictim()->GetCharmerOrOwnerPlayerOrPlayerItself()->IsGameMaster()); // or the victim/owner/charmer is not a GameMaster + if (m_regenTimer == 0) + { + bool bInCombat = IsInCombat() && (!GetVictim() || // if IsInCombat() is true and this has no victim + !EnsureVictim()->GetCharmerOrOwnerPlayerOrPlayerItself() || // or the victim/owner/charmer is not a player + !EnsureVictim()->GetCharmerOrOwnerPlayerOrPlayerItself()->IsGameMaster()); // or the victim/owner/charmer is not a GameMaster - /*if (m_regenTimer <= diff) - {*/ - if (!IsInEvadeMode() && (!bInCombat || IsPolymorphed())) // regenerate health if not in combat or if polymorphed - RegenerateHealth(); + if (!IsInEvadeMode() && (!bInCombat || IsPolymorphed() || CanNotReachTarget())) // regenerate health if not in combat or if polymorphed + RegenerateHealth(); - if (HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER)) - { - if (getPowerType() == POWER_ENERGY) - Regenerate(POWER_ENERGY); - else - RegenerateMana(); + if (HasFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER)) + { + if (getPowerType() == POWER_ENERGY) + Regenerate(POWER_ENERGY); + else + RegenerateMana(); + } + m_regenTimer = CREATURE_REGEN_INTERVAL; } - /*if (!bIsPolymorphed) // only increase the timer if not polymorphed - m_regenTimer += CREATURE_REGEN_INTERVAL - diff; + if (CanNotReachTarget() && !IsInEvadeMode() && !GetMap()->IsRaid()) + { + m_cannotReachTimer += diff; + if (m_cannotReachTimer >= CREATURE_NOPATH_EVADE_TIME) + if (IsAIEnabled) + AI()->EnterEvadeMode(CreatureAI::EVADE_REASON_NO_PATH); } - else - if (!bIsPolymorphed) // if polymorphed, skip the timer - m_regenTimer -= diff;*/ - m_regenTimer = CREATURE_REGEN_INTERVAL; break; } default: @@ -768,7 +769,7 @@ void Creature::DoFleeToGetAssistance() float radius = sWorld->getFloatConfig(CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS); if (radius >0) { - Creature* creature = NULL; + Creature* creature = nullptr; CellCoord p(Trinity::ComputeCellCoord(GetPositionX(), GetPositionY())); Cell cell(p); @@ -781,7 +782,7 @@ void Creature::DoFleeToGetAssistance() cell.Visit(p, grid_creature_searcher, *GetMap(), *this, radius); SetNoSearchAssistance(true); - UpdateSpeed(MOVE_RUN, false); + UpdateSpeed(MOVE_RUN); if (!creature) //SetFeared(true, EnsureVictim()->GetGUID(), 0, sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY)); @@ -792,6 +793,24 @@ void Creature::DoFleeToGetAssistance() } } +bool Creature::AIM_Destroy() +{ + if (m_AI_locked) + { + TC_LOG_DEBUG("scripts", "AIM_Destroy: failed to destroy, locked."); + return false; + } + + ASSERT(!i_disabledAI, + "The disabled AI wasn't cleared!"); + + delete i_AI; + i_AI = nullptr; + + IsAIEnabled = false; + return true; +} + bool Creature::AIM_Initialize(CreatureAI* ai) { // make sure nothing can change the AI during AI update @@ -801,12 +820,12 @@ bool Creature::AIM_Initialize(CreatureAI* ai) return false; } - UnitAI* oldAI = i_AI; + AIM_Destroy(); Motion_Initialize(); i_AI = ai ? ai : FactorySelector::selectAI(this); - delete oldAI; + IsAIEnabled = true; i_AI->InitializeAI(); // Initialize vehicle @@ -847,15 +866,17 @@ bool Creature::Create(ObjectGuid::LowType guidlow, Map* map, uint32 phaseMask, u //! returning correct zone id for selecting OutdoorPvP/Battlefield script Relocate(x, y, z, ang); - if (!CreateFromProto(guidlow, entry, data, vehId)) - return false; - + // Check if the position is valid before calling CreateFromProto(), otherwise we might add Auras to Creatures at + // invalid position, triggering a crash about Auras not removed in the destructor if (!IsPositionValid()) { TC_LOG_ERROR("entities.unit", "Creature::Create(): given coordinates for creature (guidlow %d, entry %d) are not valid (X: %f, Y: %f, Z: %f, O: %f)", guidlow, entry, x, y, z, ang); return false; } + if (!CreateFromProto(guidlow, entry, data, vehId)) + return false; + switch (GetCreatureTemplate()->rank) { case CREATURE_ELITE_RARE: @@ -890,7 +911,7 @@ bool Creature::Create(ObjectGuid::LowType guidlow, Map* map, uint32 phaseMask, u { SetDisplayId(displayID); SetNativeDisplayId(displayID); - SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, minfo->gender); } LastUsedScriptID = GetCreatureTemplate()->ScriptID; @@ -968,14 +989,14 @@ bool Creature::isCanTrainingAndResetTalentsOf(Player* player) const Player* Creature::GetLootRecipient() const { if (!m_lootRecipient) - return NULL; + return nullptr; return ObjectAccessor::FindConnectedPlayer(m_lootRecipient); } Group* Creature::GetLootRecipientGroup() const { if (!m_lootRecipientGroup) - return NULL; + return nullptr; return sGroupMgr->GetGroupByGUID(m_lootRecipientGroup); } @@ -983,7 +1004,7 @@ void Creature::SetLootRecipient(Unit* unit) { // set the player whose group should receive the right // to loot the creature after it dies - // should be set to NULL after the loot disappears + // should be set to nullptr after the loot disappears if (!unit) { @@ -1356,8 +1377,8 @@ bool Creature::LoadCreatureFromDB(ObjectGuid::LowType spawnId, Map* map, bool ad m_deathState = DEAD; if (CanFly()) { - float tz = map->GetHeight(GetPhaseMask(), data->posX, data->posY, data->posZ, false); - if (data->posZ - tz > 0.1f) + float tz = map->GetHeight(GetPhaseMask(), data->posX, data->posY, data->posZ, true, MAX_FALL_DISTANCE); + if (data->posZ - tz > 0.1f && Trinity::IsValidMapCoord(tz)) Relocate(data->posX, data->posY, tz); } } @@ -1607,7 +1628,7 @@ void Creature::setDeathState(DeathState s) if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY) || isWorldBoss()) SaveRespawnTime(); - ReleaseFocus(); // remove spellcast focus (this also clears unit target) + ReleaseFocus(nullptr, false); // remove spellcast focus SetTarget(ObjectGuid::Empty); // drop target - dead mobs shouldn't ever target things SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); @@ -1619,7 +1640,7 @@ void Creature::setDeathState(DeathState s) if (HasSearchedAssistance()) { SetNoSearchAssistance(false); - UpdateSpeed(MOVE_RUN, false); + UpdateSpeed(MOVE_RUN); } //Dismiss group if is leader @@ -1636,7 +1657,7 @@ void Creature::setDeathState(DeathState s) //if (IsPet()) // setActive(true); SetFullHealth(); - SetLootRecipient(NULL); + SetLootRecipient(nullptr); ResetPlayerDamageReq(); UpdateMovementFlags(); @@ -1706,7 +1727,7 @@ void Creature::Respawn(bool force) { SetDisplayId(displayID); SetNativeDisplayId(displayID); - SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, minfo->gender); } GetMotionMaster()->InitDefault(); @@ -1716,7 +1737,7 @@ void Creature::Respawn(bool force) { //reset the AI to be sure no dirty or uninitialized values will be used till next tick AI()->Reset(); - TriggerJustRespawned = true;//delay event to next tick so all creatures are created on the map before processing + m_TriggerJustRespawned = true;//delay event to next tick so all creatures are created on the map before processing } uint32 poolid = GetSpawnId() ? sPoolMgr->IsPartOfAPool<Creature>(GetSpawnId()) : 0; @@ -1807,15 +1828,15 @@ bool Creature::isWorldBoss() const if (IsPet()) return false; - return (GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_BOSS) != 0; + return (GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_BOSS_MOB) != 0; } SpellInfo const* Creature::reachWithSpellAttack(Unit* victim) { if (!victim) - return NULL; + return nullptr; - for (uint32 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i=0; i < MAX_CREATURE_SPELLS; ++i) { if (!m_spells[i]) continue; @@ -1855,15 +1876,15 @@ SpellInfo const* Creature::reachWithSpellAttack(Unit* victim) continue; return spellInfo; } - return NULL; + return nullptr; } SpellInfo const* Creature::reachWithSpellCure(Unit* victim) { if (!victim) - return NULL; + return nullptr; - for (uint32 i=0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i=0; i < MAX_CREATURE_SPELLS; ++i) { if (!m_spells[i]) continue; @@ -1902,7 +1923,7 @@ SpellInfo const* Creature::reachWithSpellCure(Unit* victim) continue; return spellInfo; } - return NULL; + return nullptr; } // select nearest hostile unit within the given distance (regardless of threat list). @@ -1912,7 +1933,7 @@ Unit* Creature::SelectNearestTarget(float dist, bool playerOnly /* = false */) c Cell cell(p); cell.SetNoCreate(); - Unit* target = NULL; + Unit* target = nullptr; { if (dist == 0.0f) @@ -1938,7 +1959,7 @@ Unit* Creature::SelectNearestTargetInAttackDistance(float dist) const Cell cell(p); cell.SetNoCreate(); - Unit* target = NULL; + Unit* target = nullptr; if (dist > MAX_VISIBILITY_DISTANCE) { @@ -1962,7 +1983,7 @@ Unit* Creature::SelectNearestTargetInAttackDistance(float dist) const Player* Creature::SelectNearestPlayer(float distance) const { - Player* target = NULL; + Player* target = nullptr; Trinity::NearestPlayerInObjectRangeCheck checker(this, distance); Trinity::PlayerLastSearcher<Trinity::NearestPlayerInObjectRangeCheck> searcher(this, target, checker); @@ -2259,7 +2280,7 @@ void Creature::SendZoneUnderAttackMessage(Player* attacker) WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4); data << (uint32)GetAreaId(); - sWorld->SendGlobalMessage(&data, NULL, (enemy_team == ALLIANCE ? HORDE : ALLIANCE)); + sWorld->SendGlobalMessage(&data, nullptr, (enemy_team == ALLIANCE ? HORDE : ALLIANCE)); } void Creature::SetInCombatWithZone() @@ -2308,10 +2329,10 @@ uint32 Creature::GetShieldBlockValue() const //dunno mob block bool Creature::HasSpell(uint32 spellID) const { uint8 i; - for (i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (i = 0; i < MAX_CREATURE_SPELLS; ++i) if (spellID == m_spells[i]) break; - return i < CREATURE_MAX_SPELLS; //broke before end of iteration of known spells + return i < MAX_CREATURE_SPELLS; //broke before end of iteration of known spells } time_t Creature::GetRespawnTimeEx() const @@ -2756,13 +2777,13 @@ void Creature::SetTarget(ObjectGuid guid) bool Creature::FocusTarget(Spell const* focusSpell, WorldObject const* target) { // already focused - if (_focusSpell) + if (m_focusSpell) return false; if ((!target || target == this) && !focusSpell->GetCastTime()) // instant cast, untargeted (or self-targeted) spell doesn't need any facing updates return false; - _focusSpell = focusSpell; + m_focusSpell = focusSpell; // "instant" creature casts that require re-targeting will be delayed by a short moment to prevent facing bugs bool shouldDelay = false; @@ -2774,43 +2795,39 @@ bool Creature::FocusTarget(Spell const* focusSpell, WorldObject const* target) SetGuidValue(UNIT_FIELD_TARGET, newTarget); if (target) SetFacingToObject(target); - + if ( // here we determine if the (relatively expensive) forced update is worth it, or whether we can afford to wait until the scheduled update tick ( // only require instant update for spells that actually have a visual focusSpell->GetSpellInfo()->SpellVisual[0] || focusSpell->GetSpellInfo()->SpellVisual[1] - ) && ( + ) && ( !focusSpell->GetCastTime() || // if the spell is instant cast focusSpell->GetSpellInfo()->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST) // client gets confused if we attempt to turn at the regularly scheduled update packet ) ) { - const MapRefManager& mapPlayers = GetMap()->GetPlayers(); - for (MapRefManager::const_iterator it = mapPlayers.begin(); it != mapPlayers.end(); ++it) - if (Player* player = (*it).GetSource()) + std::list<Player*> playersNearby; + GetPlayerListInGrid(playersNearby, GetVisibilityRange()); + for (Player* player : playersNearby) + { + // only update players that are known to the client (have already been created) + if (player->HaveAtClient(this)) { - // only update players that can both see us, and are actually in combat with us (this is a performance tradeoff) - if (player->CanSeeOrDetect(this, false, true) && IsInCombatWith(player)) - { - SendUpdateToPlayer(player); - shouldDelay = true; - } + SendUpdateToPlayer(player); + shouldDelay = true; } + } if (shouldDelay) shouldDelay = !(focusSpell->IsTriggered() || focusSpell->GetCastTime() || focusSpell->GetSpellInfo()->IsChanneled()); - } } - // tell the creature that it should reacquire its current target after the cast is done (this is handled in ::Attack) - MustReacquireTarget(); - bool canTurnDuringCast = !focusSpell->GetSpellInfo()->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST); // Face the target - we need to do this before the unit state is modified for no-turn spells if (target) SetInFront(target); else if (!canTurnDuringCast) - if(Unit* victim = GetVictim()) + if (Unit* victim = GetVictim()) SetInFront(victim); // ensure server-side orientation is correct at beginning of cast if (!canTurnDuringCast) @@ -2827,16 +2844,16 @@ bool Creature::IsFocusing(Spell const* focusSpell, bool withDelay) return false; } - if (focusSpell && (focusSpell != _focusSpell)) + if (focusSpell && (focusSpell != m_focusSpell)) return false; - if (!_focusSpell) + if (!m_focusSpell) { - if (!withDelay || !_focusDelay) + if (!withDelay || !m_focusDelay) return false; - if (GetMSTimeDiffToNow(_focusDelay) > 1000) // @todo figure out if we can get rid of this magic number somehow + if (GetMSTimeDiffToNow(m_focusDelay) > 1000) // @todo figure out if we can get rid of this magic number somehow { - _focusDelay = 0; // save checks in the future + m_focusDelay = 0; // save checks in the future return false; } } @@ -2846,20 +2863,25 @@ bool Creature::IsFocusing(Spell const* focusSpell, bool withDelay) void Creature::ReleaseFocus(Spell const* focusSpell, bool withDelay) { - if (!_focusSpell) + if (!m_focusSpell) return; // focused to something else - if (focusSpell && focusSpell != _focusSpell) + if (focusSpell && focusSpell != m_focusSpell) return; - SetGuidValue(UNIT_FIELD_TARGET, ObjectGuid::Empty); + if (IsPet()) // player pets do not use delay system + SetGuidValue(UNIT_FIELD_TARGET, GetVictim() ? EnsureVictim()->GetGUID() : ObjectGuid::Empty); + else + // tell the creature that it should reacquire its actual target after the delay expires (this is handled in ::Attack) + // player pets don't need to do this, as they automatically reacquire their target on focus release + MustReacquireTarget(); - if (_focusSpell->GetSpellInfo()->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST)) + if (m_focusSpell->GetSpellInfo()->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST)) ClearUnitState(UNIT_STATE_CANNOT_TURN); - _focusSpell = nullptr; - _focusDelay = withDelay ? getMSTime() : 0; // don't allow re-target right away to prevent visual bugs + m_focusSpell = nullptr; + m_focusDelay = (!IsPet() && withDelay) ? getMSTime() : 0; // don't allow re-target right away to prevent visual bugs } void Creature::StartPickPocketRefillTimer() diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index 49bd854ef2f..cfe637c4b21 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -22,7 +22,7 @@ #include "Common.h" #include "Unit.h" #include "UpdateMask.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" #include "LootMgr.h" #include "DatabaseEnv.h" #include "Cell.h" @@ -67,15 +67,16 @@ enum CreatureFlagsExtra CREATURE_FLAG_EXTRA_NO_SKILLGAIN | CREATURE_FLAG_EXTRA_TAUNT_DIMINISH | CREATURE_FLAG_EXTRA_ALL_DIMINISH | \ CREATURE_FLAG_EXTRA_GUARD | CREATURE_FLAG_EXTRA_IGNORE_PATHFINDING | CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ | CREATURE_FLAG_EXTRA_IMMUNITY_KNOCKBACK) -#define CREATURE_REGEN_INTERVAL 2 * IN_MILLISECONDS +static const uint32 CREATURE_REGEN_INTERVAL = 2 * IN_MILLISECONDS; +static const uint32 CREATURE_NOPATH_EVADE_TIME = 5 * IN_MILLISECONDS; -#define MAX_KILL_CREDIT 2 -#define MAX_CREATURE_MODELS 4 -#define MAX_CREATURE_QUEST_ITEMS 6 -#define CREATURE_MAX_SPELLS 8 +static const uint8 MAX_KILL_CREDIT = 2; +static const uint32 MAX_CREATURE_MODELS = 4; +static const uint32 MAX_CREATURE_QUEST_ITEMS = 6; +static const uint32 MAX_CREATURE_SPELLS = 8; // from `creature_template` table -struct CreatureTemplate +struct TC_GAME_API CreatureTemplate { uint32 Entry; uint32 DifficultyEntry[MAX_DIFFICULTY - 1]; @@ -106,7 +107,7 @@ struct CreatureTemplate uint32 unit_flags; // enum UnitFlags mask values uint32 unit_flags2; // enum UnitFlags2 mask values uint32 dynamicflags; - uint32 family; // enum CreatureFamily values (optional) + CreatureFamily family; // enum CreatureFamily values (optional) uint32 trainer_type; uint32 trainer_spell; uint32 trainer_class; @@ -117,7 +118,7 @@ struct CreatureTemplate uint32 pickpocketLootId; uint32 SkinLootId; int32 resistance[MAX_SPELL_SCHOOL]; - uint32 spells[CREATURE_MAX_SPELLS]; + uint32 spells[MAX_CREATURE_SPELLS]; uint32 PetSpellDataId; uint32 VehicleId; uint32 mingold; @@ -145,11 +146,11 @@ struct CreatureTemplate // helpers SkillType GetRequiredLootSkill() const { - if (type_flags & CREATURE_TYPEFLAGS_HERBLOOT) + if (type_flags & CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL) return SKILL_HERBALISM; - else if (type_flags & CREATURE_TYPEFLAGS_MININGLOOT) + else if (type_flags & CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL) return SKILL_MINING; - else if (type_flags & CREATURE_TYPEFLAGS_ENGINEERLOOT) + else if (type_flags & CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL) return SKILL_ENGINEERING; else return SKILL_SKINNING; // normal case @@ -157,12 +158,12 @@ struct CreatureTemplate bool IsExotic() const { - return (type_flags & CREATURE_TYPEFLAGS_EXOTIC) != 0; + return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; } bool IsTameable(bool canTameExotic) const { - if (type != CREATURE_TYPE_BEAST || family == 0 || (type_flags & CREATURE_TYPEFLAGS_TAMEABLE) == 0) + if (type != CREATURE_TYPE_BEAST || family == CREATURE_FAMILY_NONE || (type_flags & CREATURE_TYPE_FLAG_TAMEABLE_PET) == 0) return false; // if can tame exotic then can tame any tameable @@ -179,7 +180,7 @@ typedef std::unordered_map<uint32, CreatureTemplate> CreatureTemplateContainer; #pragma pack(push, 1) // Defines base stats for creatures (used to calculate HP/mana/armor/attackpower/rangedattackpower/all damage). -struct CreatureBaseStats +struct TC_GAME_API CreatureBaseStats { uint32 BaseHealth[MAX_EXPANSIONS]; uint32 BaseMana; @@ -293,7 +294,8 @@ enum InhabitTypeValues INHABIT_GROUND = 1, INHABIT_WATER = 2, INHABIT_AIR = 4, - INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR + INHABIT_ROOT = 8, + INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR | INHABIT_ROOT }; // Enums used by StringTextData::Type (CreatureEventAI) @@ -401,7 +403,7 @@ struct TrainerSpell typedef std::unordered_map<uint32 /*spellid*/, TrainerSpell> TrainerSpellMap; -struct TrainerSpellData +struct TC_GAME_API TrainerSpellData { TrainerSpellData() : trainerType(0) { } ~TrainerSpellData() { spellList.clear(); } @@ -421,7 +423,7 @@ struct TrainerSpellData typedef std::vector<uint8> CreatureTextRepeatIds; typedef std::unordered_map<uint8, CreatureTextRepeatIds> CreatureTextRepeatGroup; -class Creature : public Unit, public GridObject<Creature>, public MapObject +class TC_GAME_API Creature : public Unit, public GridObject<Creature>, public MapObject { public: @@ -475,11 +477,13 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject uint8 getLevelForTarget(WorldObject const* target) const override; // overwrite Unit::getLevelForTarget for boss level support bool IsInEvadeMode() const { return HasUnitState(UNIT_STATE_EVADE); } + bool IsEvadingAttacks() const { return IsInEvadeMode() || CanNotReachTarget(); } + bool AIM_Destroy(); bool AIM_Initialize(CreatureAI* ai = NULL); void Motion_Initialize(); - CreatureAI* AI() const { return (CreatureAI*)i_AI; } + CreatureAI* AI() const { return reinterpret_cast<CreatureAI*>(i_AI); } bool SetWalk(bool enable) override; bool SetDisableGravity(bool disable, bool packetOnly = false) override; @@ -566,7 +570,7 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject SpellInfo const* reachWithSpellAttack(Unit* victim); SpellInfo const* reachWithSpellCure(Unit* victim); - uint32 m_spells[CREATURE_MAX_SPELLS]; + uint32 m_spells[MAX_CREATURE_SPELLS]; bool CanStartAttack(Unit const* u, bool force) const; float GetAttackDistance(Unit const* player) const; @@ -594,6 +598,7 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject void RemoveCorpse(bool setSpawnTime = true); void DespawnOrUnsummon(uint32 msTimeToDespawn = 0); + void DespawnOrUnsummon(Milliseconds const& time) { DespawnOrUnsummon(uint32(time.count())); } time_t const& GetRespawnTime() const { return m_respawnTime; } time_t GetRespawnTimeEx() const; @@ -631,6 +636,15 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject virtual uint8 GetPetAutoSpellSize() const { return MAX_SPELL_CHARM; } virtual uint32 GetPetAutoSpellOnPos(uint8 pos) const; + void SetCannotReachTarget(bool cannotReach) + { + if (cannotReach == m_cannotReachTarget) + return; + m_cannotReachTarget = cannotReach; + m_cannotReachTimer = 0; + } + bool CanNotReachTarget() const { return m_cannotReachTarget; } + void SetPosition(float x, float y, float z, float o); void SetPosition(const Position &pos) { SetPosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation()); } @@ -718,6 +732,8 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject bool m_AlreadyCallAssistance; bool m_AlreadySearchedAssistance; bool m_regenHealth; + bool m_cannotReachTarget; + uint32 m_cannotReachTimer; bool m_AI_locked; SpellSchoolMask m_meleeDamageSchoolMask; @@ -746,15 +762,15 @@ class Creature : public Unit, public GridObject<Creature>, public MapObject //Formation var CreatureGroup* m_formation; - bool TriggerJustRespawned; + bool m_TriggerJustRespawned; - Spell const* _focusSpell; ///> Locks the target during spell cast for proper facing - uint32 _focusDelay; + Spell const* m_focusSpell; ///> Locks the target during spell cast for proper facing + uint32 m_focusDelay; CreatureTextRepeatGroup m_textRepeat; }; -class AssistDelayEvent : public BasicEvent +class TC_GAME_API AssistDelayEvent : public BasicEvent { public: AssistDelayEvent(ObjectGuid victim, Unit& owner) : BasicEvent(), m_victim(victim), m_owner(owner) { } @@ -769,7 +785,7 @@ class AssistDelayEvent : public BasicEvent Unit& m_owner; }; -class ForcedDespawnDelayEvent : public BasicEvent +class TC_GAME_API ForcedDespawnDelayEvent : public BasicEvent { public: ForcedDespawnDelayEvent(Creature& owner) : BasicEvent(), m_owner(owner) { } diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index 9f26c927374..0c41089efce 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -30,6 +30,12 @@ FormationMgr::~FormationMgr() delete itr->second; } +FormationMgr* FormationMgr::instance() +{ + static FormationMgr instance; + return &instance; +} + void FormationMgr::AddCreatureToGroup(uint32 leaderGuid, Creature* creature) { Map* map = creature->FindMap(); diff --git a/src/server/game/Entities/Creature/CreatureGroups.h b/src/server/game/Entities/Creature/CreatureGroups.h index 7b16585a996..14472a30293 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.h +++ b/src/server/game/Entities/Creature/CreatureGroups.h @@ -38,18 +38,14 @@ struct FormationInfo typedef std::unordered_map<uint32/*memberDBGUID*/, FormationInfo*> CreatureGroupInfoType; -class FormationMgr +class TC_GAME_API FormationMgr { private: FormationMgr() { } ~FormationMgr(); public: - static FormationMgr* instance() - { - static FormationMgr instance; - return &instance; - } + static FormationMgr* instance(); void AddCreatureToGroup(uint32 group_id, Creature* creature); void RemoveCreatureFromGroup(CreatureGroup* group, Creature* creature); @@ -57,7 +53,7 @@ class FormationMgr CreatureGroupInfoType CreatureGroupMap; }; -class CreatureGroup +class TC_GAME_API CreatureGroup { private: Creature* m_leader; //Important do not forget sometimes to work with pointers instead synonims :D:D diff --git a/src/server/game/Entities/Creature/GossipDef.h b/src/server/game/Entities/Creature/GossipDef.h index 1e64e83c86a..01b27032286 100644 --- a/src/server/game/Entities/Creature/GossipDef.h +++ b/src/server/game/Entities/Creature/GossipDef.h @@ -157,7 +157,7 @@ struct QuestMenuItem typedef std::vector<QuestMenuItem> QuestMenuItemList; -class GossipMenu +class TC_GAME_API GossipMenu { public: GossipMenu(); @@ -222,7 +222,7 @@ class GossipMenu LocaleConstant _locale; }; -class QuestMenu +class TC_GAME_API QuestMenu { public: QuestMenu(); @@ -252,7 +252,7 @@ class QuestMenu QuestMenuItemList _questMenuItems; }; -class PlayerMenu +class TC_GAME_API PlayerMenu { public: explicit PlayerMenu(WorldSession* session); diff --git a/src/server/game/Entities/Creature/TemporarySummon.cpp b/src/server/game/Entities/Creature/TemporarySummon.cpp index 8bf3a1e2846..12e3af3c290 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.cpp +++ b/src/server/game/Entities/Creature/TemporarySummon.cpp @@ -227,6 +227,11 @@ void TempSummon::InitSummon() } } +void TempSummon::UpdateObjectVisibilityOnCreate() +{ + WorldObject::UpdateObjectVisibility(true); +} + void TempSummon::SetTempSummonType(TempSummonType type) { m_type = type; diff --git a/src/server/game/Entities/Creature/TemporarySummon.h b/src/server/game/Entities/Creature/TemporarySummon.h index 6d058f405a8..87cb883b261 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.h +++ b/src/server/game/Entities/Creature/TemporarySummon.h @@ -37,7 +37,7 @@ struct TempSummonData uint32 time; ///< Despawn time, usable only with certain temp summon types }; -class TempSummon : public Creature +class TC_GAME_API TempSummon : public Creature { public: explicit TempSummon(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject); @@ -45,6 +45,7 @@ class TempSummon : public Creature void Update(uint32 time) override; virtual void InitStats(uint32 lifetime); virtual void InitSummon(); + void UpdateObjectVisibilityOnCreate() override; virtual void UnSummon(uint32 msTime = 0); void RemoveFromWorld() override; void SetTempSummonType(TempSummonType type); @@ -63,7 +64,7 @@ class TempSummon : public Creature ObjectGuid m_summonerGUID; }; -class Minion : public TempSummon +class TC_GAME_API Minion : public TempSummon { public: Minion(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject); @@ -81,7 +82,7 @@ class Minion : public TempSummon float m_followAngle; }; -class Guardian : public Minion +class TC_GAME_API Guardian : public Minion { public: Guardian(SummonPropertiesEntry const* properties, Unit* owner, bool isWorldObject); @@ -105,7 +106,7 @@ class Guardian : public Minion float m_statFromOwner[MAX_STATS]; }; -class Puppet : public Minion +class TC_GAME_API Puppet : public Minion { public: Puppet(SummonPropertiesEntry const* properties, Unit* owner); @@ -115,7 +116,7 @@ class Puppet : public Minion void RemoveFromWorld() override; }; -class ForcedUnsummonDelayEvent : public BasicEvent +class TC_GAME_API ForcedUnsummonDelayEvent : public BasicEvent { public: ForcedUnsummonDelayEvent(TempSummon& owner) : BasicEvent(), m_owner(owner) { } diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.h b/src/server/game/Entities/DynamicObject/DynamicObject.h index 9443a5b5b89..d7c1f0190fd 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.h +++ b/src/server/game/Entities/DynamicObject/DynamicObject.h @@ -32,7 +32,7 @@ enum DynamicObjectType DYNAMIC_OBJECT_FARSIGHT_FOCUS = 0x2 }; -class DynamicObject : public WorldObject, public GridObject<DynamicObject>, public MapObject +class TC_GAME_API DynamicObject : public WorldObject, public GridObject<DynamicObject>, public MapObject { public: DynamicObject(bool isWorldObject); diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index 1acfeacbf83..ba336303a35 100644 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -34,7 +34,7 @@ #include "Transport.h" GameObject::GameObject() : WorldObject(false), MapObject(), - m_model(NULL), m_goValue(), m_AI(NULL) + m_model(nullptr), m_goValue(), m_AI(nullptr) { m_objectType |= TYPEMASK_GAMEOBJECT; m_objectTypeId = TYPEID_GAMEOBJECT; @@ -49,11 +49,11 @@ GameObject::GameObject() : WorldObject(false), MapObject(), m_usetimes = 0; m_spellId = 0; m_cooldownTime = 0; - m_goInfo = NULL; - m_goData = NULL; + m_goInfo = nullptr; + m_goData = nullptr; + m_packedRotation = 0; m_spawnId = 0; - m_rotation = 0; m_lootRecipientGroup = 0; m_groupLootTimer = 0; @@ -71,9 +71,15 @@ GameObject::~GameObject() // CleanupsBeforeDelete(); } -bool GameObject::AIM_Initialize() +void GameObject::AIM_Destroy() { delete m_AI; + m_AI = nullptr; +} + +bool GameObject::AIM_Initialize() +{ + AIM_Destroy(); m_AI = FactorySelector::SelectGameObjectAI(this); @@ -167,16 +173,16 @@ void GameObject::RemoveFromWorld() } } -bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state, uint32 artKit) +bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit /*= 0*/) { ASSERT(map); SetMap(map); - Relocate(x, y, z, ang); - m_stationaryPosition.Relocate(x, y, z, ang); + Relocate(pos); + m_stationaryPosition.Relocate(pos); if (!IsPositionValid()) { - TC_LOG_ERROR("misc", "Gameobject (GUID: %u Entry: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)", guidlow, name_id, x, y); + TC_LOG_ERROR("misc", "Gameobject (GUID: %u Entry: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)", guidlow, name_id, pos.GetPositionX(), pos.GetPositionY()); return false; } @@ -193,7 +199,7 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(name_id); if (!goinfo) { - TC_LOG_ERROR("sql.sql", "Gameobject (GUID: %u Entry: %u) not created: non-existing entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f)", guidlow, name_id, map->GetId(), x, y, z); + TC_LOG_ERROR("sql.sql", "Gameobject (GUID: %u Entry: %u) not created: non-existing entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f)", guidlow, name_id, map->GetId(), pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); return false; } @@ -216,10 +222,15 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u return false; } - SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0); - SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1); + SetWorldRotation(rotation); + GameObjectAddon const* gameObjectAddon = sObjectMgr->GetGameObjectAddon(GetSpawnId()); + + // For most of gameobjects is (0, 0, 0, 1) quaternion, there are only some transports with not standard rotation + G3D::Quat parentRotation; + if (gameObjectAddon) + parentRotation = gameObjectAddon->ParentRotation; - UpdateRotationFields(rotation2, rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION, GAMEOBJECT_PARENTROTATION+2/3 + SetParentRotation(parentRotation); SetObjectScale(goinfo->size); @@ -279,13 +290,10 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u break; } - if (GameObjectAddon const* addon = sObjectMgr->GetGameObjectAddon(GetSpawnId())) + if (gameObjectAddon && gameObjectAddon->InvisibilityValue) { - if (addon->InvisibilityValue) - { - m_invisibility.AddFlag(addon->invisibilityType); - m_invisibility.AddValue(addon->invisibilityType, addon->InvisibilityValue); - } + m_invisibility.AddFlag(gameObjectAddon->invisibilityType); + m_invisibility.AddValue(gameObjectAddon->invisibilityType, gameObjectAddon->InvisibilityValue); } LastUsedScriptID = GetGOInfo()->ScriptId; @@ -490,7 +498,7 @@ void GameObject::Update(uint32 diff) radius = goInfo->trap.diameter / 2.f; // Pointer to appropriate target if found any - Unit* target = NULL; + Unit* target = nullptr; /// @todo this hack with search required until GO casting not implemented if (Unit* owner = GetOwner()) @@ -505,7 +513,7 @@ void GameObject::Update(uint32 diff) else { // Environmental trap: Any player - Player* player = NULL; + Player* player = nullptr; Trinity::AnyPlayerInObjectRangeCheck checker(this, radius); Trinity::PlayerSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(this, player, checker); VisitNearbyWorldObject(radius, searcher); @@ -565,8 +573,8 @@ void GameObject::Update(uint32 diff) GameObjectTemplate const* goInfo = GetGOInfo(); if (goInfo->trap.type == 2 && goInfo->trap.spellId) { - /// @todo NULL target won't work for target type 1 - CastSpell(NULL, goInfo->trap.spellId); + /// @todo nullptr target won't work for target type 1 + CastSpell(nullptr, goInfo->trap.spellId); SetLootState(GO_JUST_DEACTIVATED); } else if (Unit* target = ObjectAccessor::GetUnit(*this, m_lootStateUnitGUID)) @@ -774,10 +782,7 @@ void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) data.posY = GetPositionY(); data.posZ = GetPositionZ(); data.orientation = GetOrientation(); - data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0); - data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1); - data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2); - data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3); + data.rotation = m_worldRotation; data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime; data.animprogress = GetGoAnimProgress(); data.go_state = GetGoState(); @@ -803,10 +808,10 @@ void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) stmt->setFloat(index++, GetPositionY()); stmt->setFloat(index++, GetPositionZ()); stmt->setFloat(index++, GetOrientation()); - stmt->setFloat(index++, GetFloatValue(GAMEOBJECT_PARENTROTATION)); - stmt->setFloat(index++, GetFloatValue(GAMEOBJECT_PARENTROTATION+1)); - stmt->setFloat(index++, GetFloatValue(GAMEOBJECT_PARENTROTATION+2)); - stmt->setFloat(index++, GetFloatValue(GAMEOBJECT_PARENTROTATION+3)); + stmt->setFloat(index++, m_worldRotation.x); + stmt->setFloat(index++, m_worldRotation.y); + stmt->setFloat(index++, m_worldRotation.z); + stmt->setFloat(index++, m_worldRotation.w); stmt->setInt32(index++, int32(m_respawnDelayTime)); stmt->setUInt8(index++, GetGoAnimProgress()); stmt->setUInt8(index++, uint8(GetGoState())); @@ -828,22 +833,14 @@ bool GameObject::LoadGameObjectFromDB(ObjectGuid::LowType spawnId, Map* map, boo uint32 entry = data->id; //uint32 map_id = data->mapid; // already used before call uint32 phaseMask = data->phaseMask; - float x = data->posX; - float y = data->posY; - float z = data->posZ; - float ang = data->orientation; - - float rotation0 = data->rotation0; - float rotation1 = data->rotation1; - float rotation2 = data->rotation2; - float rotation3 = data->rotation3; + Position pos(data->posX, data->posY, data->posZ, data->orientation); uint32 animprogress = data->animprogress; GOState go_state = data->go_state; uint32 artKit = data->artKit; m_spawnId = spawnId; - if (!Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state, artKit)) + if (!Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, phaseMask, pos, data->rotation, animprogress, go_state, artKit)) return false; if (data->spawntimesecs >= 0) @@ -862,7 +859,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(NULL)) + if (m_respawnTime && m_respawnTime <= time(nullptr)) { m_respawnTime = 0; GetMap()->RemoveGORespawnTime(m_spawnId); @@ -1087,7 +1084,7 @@ void GameObject::TriggeringLinkedGameObject(uint32 trapEntry, Unit* target) float range = float(target->GetSpellMaxRangeForTarget(GetOwner(), trapSpell)); // search nearest linked GO - GameObject* trapGO = NULL; + GameObject* trapGO = nullptr; { // using original GO distance CellCoord p(Trinity::ComputeCellCoord(GetPositionX(), GetPositionY())); @@ -1107,7 +1104,7 @@ void GameObject::TriggeringLinkedGameObject(uint32 trapEntry, Unit* target) GameObject* GameObject::LookupFishingHoleAround(float range) { - GameObject* ok = NULL; + GameObject* ok = nullptr; CellCoord p(Trinity::ComputeCellCoord(GetPositionX(), GetPositionY())); Cell cell(p); @@ -1130,7 +1127,7 @@ void GameObject::ResetDoorOrButton() m_cooldownTime = 0; } -void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */, Unit* user /*=NULL*/) +void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */, Unit* user /*=nullptr*/) { if (m_lootState != GO_READY) return; @@ -1154,7 +1151,7 @@ void GameObject::SetGoArtKit(uint8 kit) void GameObject::SetGoArtKit(uint8 artkit, GameObject* go, ObjectGuid::LowType lowguid) { - const GameObjectData* data = NULL; + const GameObjectData* data = nullptr; if (go) { go->SetGoArtKit(artkit); @@ -1282,8 +1279,8 @@ void GameObject::Use(Unit* user) { if (Player* ChairUser = ObjectAccessor::FindPlayer(itr->second)) { - if (ChairUser->IsSitState() && ChairUser->getStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f) - continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->getStandState() != UNIT_STAND_STATE_SIT check is required. + if (ChairUser->IsSitState() && ChairUser->GetStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f) + continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->GetStandState() != UNIT_STAND_STATE_SIT check is required. else itr->second.Clear(); // This seat is unoccupied. } @@ -1380,7 +1377,7 @@ void GameObject::Use(Unit* user) // cast this spell later if provided spellId = info->goober.spellId; - spellCaster = NULL; + spellCaster = nullptr; break; } @@ -1447,11 +1444,11 @@ void GameObject::Use(Unit* user) TC_LOG_DEBUG("misc", "Fishing check (skill: %i zone min skill: %i chance %i roll: %i", skill, zone_skill, chance, roll); - // but you will likely cause junk in areas that require a high fishing skill (not yet implemented) + player->UpdateFishingSkill(); + + // but you will likely cause junk in areas that require a high fishing skill if (chance >= roll) { - player->UpdateFishingSkill(); - /// @todo I do not understand this hack. Need some explanation. // prevent removing GO at spell cancel RemoveFromOwner(); @@ -1499,7 +1496,7 @@ void GameObject::Use(Unit* user) GameObjectTemplate const* info = GetGOInfo(); - Player* m_ritualOwner = NULL; + Player* m_ritualOwner = nullptr; if (m_ritualOwnerGUID) m_ritualOwner = ObjectAccessor::FindPlayer(m_ritualOwnerGUID); @@ -1863,7 +1860,7 @@ bool GameObject::IsInRange(float x, float y, float z, float radius) const && dz < info->maxZ + radius && dz > info->minZ - radius; } -void GameObject::EventInform(uint32 eventId, WorldObject* invoker /*= NULL*/) +void GameObject::EventInform(uint32 eventId, WorldObject* invoker /*= nullptr*/) { if (!eventId) return; @@ -1893,37 +1890,41 @@ std::string const & GameObject::GetNameForLocaleIdx(LocaleConstant loc_idx) cons return GetName(); } -void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/) +void GameObject::UpdatePackedRotation() { - static double const atan_pow = atan(pow(2.0f, -20.0f)); - - double f_rot1 = std::sin(GetOrientation() / 2.0f); - double f_rot2 = std::cos(GetOrientation() / 2.0f); + static const int32 PACK_YZ = 1 << 20; + static const int32 PACK_X = PACK_YZ << 1; - int64 i_rot1 = int64(f_rot1 / atan_pow *(f_rot2 >= 0 ? 1.0f : -1.0f)); - int64 rotation = (i_rot1 << 43 >> 43) & 0x00000000001FFFFF; + static const int32 PACK_YZ_MASK = (PACK_YZ << 1) - 1; + static const int32 PACK_X_MASK = (PACK_X << 1) - 1; - //float f_rot2 = std::sin(0.0f / 2.0f); - //int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f)); - //rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000; - - //float f_rot3 = std::sin(0.0f / 2.0f); - //int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f)); - //rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000; + int8 w_sign = (m_worldRotation.w >= 0.f ? 1 : -1); + int64 x = int32(m_worldRotation.x * PACK_X) * w_sign & PACK_X_MASK; + int64 y = int32(m_worldRotation.y * PACK_YZ) * w_sign & PACK_YZ_MASK; + int64 z = int32(m_worldRotation.z * PACK_YZ) * w_sign & PACK_YZ_MASK; + m_packedRotation = z | (y << 21) | (x << 42); +} - m_rotation = rotation; +void GameObject::SetWorldRotation(G3D::Quat const& rot) +{ + m_worldRotation = rot.toUnit(); + UpdatePackedRotation(); +} - if (rotation2 == 0.0f && rotation3 == 0.0f) - { - rotation2 = (float)f_rot1; - rotation3 = (float)f_rot2; - } +void GameObject::SetParentRotation(G3D::Quat const& rotation) +{ + SetFloatValue(GAMEOBJECT_PARENTROTATION + 0, rotation.x); + SetFloatValue(GAMEOBJECT_PARENTROTATION + 1, rotation.y); + SetFloatValue(GAMEOBJECT_PARENTROTATION + 2, rotation.z); + SetFloatValue(GAMEOBJECT_PARENTROTATION + 3, rotation.w); +} - SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2); - SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3); +void GameObject::SetWorldRotationAngles(float z_rot, float y_rot, float x_rot) +{ + SetWorldRotation(G3D::Quat(G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot))); } -void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= NULL*/, uint32 spellId /*= 0*/) +void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= nullptr*/, uint32 spellId /*= 0*/) { if (!m_goValue.Building.MaxHealth || !change) return; @@ -1942,7 +1943,7 @@ void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= NULL*/, u // Set the health bar, value = 255 * healthPct; SetGoAnimProgress(m_goValue.Building.Health * 255 / m_goValue.Building.MaxHealth); - Player* player = attackerOrHealer ? attackerOrHealer->GetCharmerOrOwnerPlayerOrPlayerItself() : NULL; + Player* player = attackerOrHealer ? attackerOrHealer->GetCharmerOrOwnerPlayerOrPlayerItself() : nullptr; // dealing damage, send packet if (player) @@ -1973,7 +1974,7 @@ void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= NULL*/, u SetDestructibleState(newState, player, false); } -void GameObject::SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker /*= NULL*/, bool setHealth /*= false*/) +void GameObject::SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker /*= nullptr*/, bool setHealth /*= false*/) { // the user calling this must know he is already operating on destructible gameobject ASSERT(GetGoType() == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING); @@ -1998,7 +1999,7 @@ void GameObject::SetDestructibleState(GameObjectDestructibleState state, Player* RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); - uint32 modelId = m_goInfo->building.damagedDisplayId; + uint32 modelId = m_goInfo->displayId; if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) if (modelData->DamagedDisplayId) modelId = modelData->DamagedDisplayId; @@ -2026,7 +2027,7 @@ void GameObject::SetDestructibleState(GameObjectDestructibleState state, Player* RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); - uint32 modelId = m_goInfo->building.destroyedDisplayId; + uint32 modelId = m_goInfo->displayId; if (DestructibleModelDataEntry const* modelData = sDestructibleModelDataStore.LookupEntry(m_goInfo->building.destructibleData)) if (modelData->DestroyedDisplayId) modelId = modelData->DestroyedDisplayId; @@ -2155,14 +2156,14 @@ void GameObject::UpdateModel() Player* GameObject::GetLootRecipient() const { if (!m_lootRecipient) - return NULL; + return nullptr; return ObjectAccessor::FindConnectedPlayer(m_lootRecipient); } Group* GameObject::GetLootRecipientGroup() const { if (!m_lootRecipientGroup) - return NULL; + return nullptr; return sGroupMgr->GetGroupByGUID(m_lootRecipientGroup); } @@ -2170,7 +2171,7 @@ void GameObject::SetLootRecipient(Unit* unit) { // set the player whose group should receive the right // to loot the creature after it dies - // should be set to NULL after the loot disappears + // should be set to nullptr after the loot disappears if (!unit) { @@ -2289,7 +2290,7 @@ void GameObject::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* t data->append(fieldBuffer); } -void GameObject::GetRespawnPosition(float &x, float &y, float &z, float* ori /* = NULL*/) const +void GameObject::GetRespawnPosition(float &x, float &y, float &z, float* ori /* = nullptr*/) const { if (m_spawnId) { diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index 7be78556a50..a271512629b 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -25,6 +25,7 @@ #include "Object.h" #include "LootMgr.h" #include "DatabaseEnv.h" +#include <G3D/Quat.h> class GameObjectAI; class Group; @@ -57,6 +58,7 @@ struct GameObjectTemplate uint32 openTextID; //4 can be used to replace castBarCaption? uint32 closeTextID; //5 uint32 ignoredByPathing; //6 + uint32 conditionID1; //7 } door; //1 GAMEOBJECT_TYPE_BUTTON struct @@ -70,6 +72,7 @@ struct GameObjectTemplate uint32 openTextID; //6 can be used to replace castBarCaption? uint32 closeTextID; //7 uint32 losOK; //8 + uint32 conditionID1; //9 } button; //2 GAMEOBJECT_TYPE_QUESTGIVER struct @@ -84,6 +87,7 @@ struct GameObjectTemplate uint32 losOK; //7 uint32 allowMounted; //8 Is usable while on mount/vehicle. (0/1) uint32 large; //9 + uint32 conditionID1; //10 } questgiver; //3 GAMEOBJECT_TYPE_CHEST struct @@ -105,6 +109,7 @@ struct GameObjectTemplate uint32 openTextID; //14 can be used to replace castBarCaption? uint32 groupLootRules; //15 uint32 floatingTooltip; //16 + uint32 conditionID1; //17 } chest; //4 GAMEOBJECT_TYPE_BINDER - empty //5 GAMEOBJECT_TYPE_GENERIC @@ -116,6 +121,7 @@ struct GameObjectTemplate uint32 large; //3 uint32 floatOnWater; //4 int32 questID; //5 + uint32 conditionID1; //6 } _generic; //6 GAMEOBJECT_TYPE_TRAP struct @@ -135,6 +141,7 @@ struct GameObjectTemplate uint32 openTextID; //12 can be used to replace castBarCaption? uint32 closeTextID; //13 uint32 ignoreTotems; //14 + uint32 conditionID1; //15 } trap; //7 GAMEOBJECT_TYPE_CHAIR struct @@ -143,6 +150,7 @@ struct GameObjectTemplate uint32 height; //1 uint32 onlyCreatorUse; //2 uint32 triggeredEvent; //3 + uint32 conditionID1; //4 } chair; //8 GAMEOBJECT_TYPE_SPELL_FOCUS struct @@ -154,6 +162,8 @@ struct GameObjectTemplate uint32 questID; //4 uint32 large; //5 uint32 floatingTooltip; //6 + uint32 floatOnWater; //7 + uint32 conditionID1; //8 } spellFocus; //9 GAMEOBJECT_TYPE_TEXT struct @@ -162,6 +172,7 @@ struct GameObjectTemplate uint32 language; //1 uint32 pageMaterial; //2 uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) + uint32 conditionID1; //4 } text; //10 GAMEOBJECT_TYPE_GOOBER struct @@ -187,6 +198,8 @@ struct GameObjectTemplate uint32 floatingTooltip; //18 uint32 gossipID; //19 uint32 WorldStateSetsState; //20 + uint32 floatOnWater; //21 + uint32 conditionID1; //22 } goober; //11 GAMEOBJECT_TYPE_TRANSPORT struct @@ -196,6 +209,7 @@ struct GameObjectTemplate uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 uint32 pause1EventID; //3 uint32 pause2EventID; //4 + uint32 mapID; //5 } transport; //12 GAMEOBJECT_TYPE_AREADAMAGE struct @@ -216,6 +230,7 @@ struct GameObjectTemplate uint32 cinematicId; //1 uint32 eventID; //2 uint32 openTextID; //3 can be used to replace castBarCaption? + uint32 conditionID1; //4 } camera; //14 GAMEOBJECT_TYPE_MAPOBJECT - empty //15 GAMEOBJECT_TYPE_MO_TRANSPORT @@ -244,9 +259,14 @@ struct GameObjectTemplate uint32 casterTargetSpellTargets; //5 uint32 castersGrouped; //6 uint32 ritualNoTargetCheck; //7 + uint32 conditionID1; //8 } summoningRitual; - //19 GAMEOBJECT_TYPE_MAILBOX - empty - //20 GAMEOBJECT_TYPE_DONOTUSE - empty + //19 GAMEOBJECT_TYPE_MAILBOX + struct + { + uint32 conditionID1; //0 + } mailbox; + //20 GAMEOBJECT_TYPE_DO_NOT_USE - empty //21 GAMEOBJECT_TYPE_GUARDPOST struct { @@ -261,6 +281,7 @@ struct GameObjectTemplate uint32 partyOnly; //2 uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) uint32 large; //4 + uint32 conditionID1; //5 } spellcaster; //23 GAMEOBJECT_TYPE_MEETINGSTONE struct @@ -280,6 +301,7 @@ struct GameObjectTemplate uint32 noDamageImmune; //5 uint32 openTextID; //6 uint32 losOK; //7 + uint32 conditionID1; //8 } flagstand; //25 GAMEOBJECT_TYPE_FISHINGHOLE struct @@ -358,21 +380,21 @@ struct GameObjectTemplate { uint32 intactNumHits; //0 uint32 creditProxyCreature; //1 - uint32 state1Name; //2 + uint32 empty1; //2 uint32 intactEvent; //3 - uint32 damagedDisplayId; //4 + uint32 empty2; //4 uint32 damagedNumHits; //5 uint32 empty3; //6 uint32 empty4; //7 uint32 empty5; //8 uint32 damagedEvent; //9 - uint32 destroyedDisplayId; //10 + uint32 empty6; //10 uint32 empty7; //11 uint32 empty8; //12 uint32 empty9; //13 uint32 destroyedEvent; //14 uint32 empty10; //15 - uint32 debuildingTimeSecs; //16 + uint32 rebuildingTimeSecs; //16 uint32 empty11; //17 uint32 destructibleData; //18 uint32 rebuildingEvent; //19 @@ -381,7 +403,11 @@ struct GameObjectTemplate uint32 damageEvent; //22 uint32 empty14; //23 } building; - //34 GAMEOBJECT_TYPE_GUILDBANK - empty + //34 GAMEOBJECT_TYPE_GUILDBANK + struct + { + uint32 conditionID1; //0 + } guildbank; //35 GAMEOBJECT_TYPE_TRAPDOOR struct { @@ -578,6 +604,7 @@ struct GameObjectLocale // `gameobject_addon` table struct GameObjectAddon { + G3D::Quat ParentRotation; InvisibilityType invisibilityType; uint32 InvisibilityValue; }; @@ -597,8 +624,7 @@ enum GOState // from `gameobject` struct GameObjectData { - explicit GameObjectData() : id(0), mapid(0), phaseMask(0), posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), - rotation0(0.0f), rotation1(0.0f), rotation2(0.0f), rotation3(0.0f), spawntimesecs(0), + explicit GameObjectData() : id(0), mapid(0), phaseMask(0), posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), animprogress(0), go_state(GO_STATE_ACTIVE), spawnMask(0), artKit(0), dbData(true) { } uint32 id; // entry in gamobject_template uint16 mapid; @@ -607,10 +633,7 @@ struct GameObjectData float posY; float posZ; float orientation; - float rotation0; - float rotation1; - float rotation2; - float rotation3; + G3D::Quat rotation; int32 spawntimesecs; uint32 animprogress; GOState go_state; @@ -640,7 +663,7 @@ class GameObjectModel; // 5 sec for bobber catch #define FISHING_BOBBER_READY_TIME 5 -class GameObject : public WorldObject, public GridObject<GameObject>, public MapObject +class TC_GAME_API GameObject : public WorldObject, public GridObject<GameObject>, public MapObject { public: explicit GameObject(); @@ -652,7 +675,7 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map void RemoveFromWorld() override; void CleanupsBeforeDelete(bool finalCleanup = true) override; - bool Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state, uint32 artKit = 0); + bool Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); void Update(uint32 p_time) override; GameObjectTemplate const* GetGOInfo() const { return m_goInfo; } GameObjectData const* GetGOData() const { return m_goData; } @@ -664,7 +687,11 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map ObjectGuid::LowType GetSpawnId() const { return m_spawnId; } - void UpdateRotationFields(float rotation2 = 0.0f, float rotation3 = 0.0f); + // z_rot, y_rot, x_rot - rotation angles around z, y and x axes + void SetWorldRotationAngles(float z_rot, float y_rot, float x_rot); + void SetWorldRotation(G3D::Quat const& rot); + void SetParentRotation(G3D::Quat const& rotation); // transforms(rotates) transport's path + int64 GetPackedWorldRotation() const { return m_packedRotation; } // overwrite WorldObject function for proper name localization std::string const& GetNameForLocaleIdx(LocaleConstant locale_idx) const override; @@ -822,7 +849,6 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map void EventInform(uint32 eventId, WorldObject* invoker = NULL); - uint64 GetRotation() const { return m_rotation; } virtual uint32 GetScriptId() const { return GetGOInfo()->ScriptId; } GameObjectAI* AI() const { return m_AI; } @@ -849,8 +875,10 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map void UpdateModelPosition(); - protected: + void AIM_Destroy(); bool AIM_Initialize(); + + protected: GameObjectModel* CreateModel(); void UpdateModel(); // updates model in case displayId were changed uint32 m_spellId; @@ -875,7 +903,8 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map GameObjectData const* m_goData; GameObjectValue m_goValue; - uint64 m_rotation; + int64 m_packedRotation; + G3D::Quat m_worldRotation; Position m_stationaryPosition; ObjectGuid m_lootRecipient; @@ -884,6 +913,7 @@ class GameObject : public WorldObject, public GridObject<GameObject>, public Map private: void RemoveFromOwner(); void SwitchDoorOrButton(bool activate, bool alternative = false); + void UpdatePackedRotation(); //! Object distance/size - overridden from Object::_IsWithinDist. Needs to take in account proper GO size. bool _IsWithinDist(WorldObject const* obj, float dist2compare, bool /*is3D*/) const override diff --git a/src/server/game/Entities/Item/Container/Bag.h b/src/server/game/Entities/Item/Container/Bag.h index 5bfafa4238c..8f84dc3e5b3 100644 --- a/src/server/game/Entities/Item/Container/Bag.h +++ b/src/server/game/Entities/Item/Container/Bag.h @@ -23,9 +23,9 @@ #define MAX_BAG_SIZE 36 // 2.0.12 #include "Item.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" -class Bag : public Item +class TC_GAME_API Bag : public Item { public: diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 70fa4714547..a8dad0b2fbc 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -447,8 +447,7 @@ bool Item::LoadFromDB(ObjectGuid::LowType guid, ObjectGuid owner_guid, Field* fi need_save = true; } - std::string enchants = fields[6].GetString(); - _LoadIntoDataField(enchants.c_str(), ITEM_FIELD_ENCHANTMENT_1_1, MAX_ENCHANTMENT_SLOT * MAX_ENCHANTMENT_OFFSET); + _LoadIntoDataField(fields[6].GetString(), ITEM_FIELD_ENCHANTMENT_1_1, MAX_ENCHANTMENT_SLOT * MAX_ENCHANTMENT_OFFSET); SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, fields[7].GetInt16()); // recalculate suffix factor if (GetItemRandomPropertyId() < 0) @@ -520,41 +519,11 @@ Player* Item::GetOwner()const return ObjectAccessor::FindPlayer(GetOwnerGUID()); } +// Just a "legacy shortcut" for proto->GetSkill() uint32 Item::GetSkill() { - const static uint32 item_weapon_skills[MAX_ITEM_SUBCLASS_WEAPON] = - { - SKILL_AXES, SKILL_2H_AXES, SKILL_BOWS, SKILL_GUNS, SKILL_MACES, - SKILL_2H_MACES, SKILL_POLEARMS, SKILL_SWORDS, SKILL_2H_SWORDS, 0, - SKILL_STAVES, 0, 0, SKILL_FIST_WEAPONS, 0, - SKILL_DAGGERS, SKILL_THROWN, SKILL_ASSASSINATION, SKILL_CROSSBOWS, SKILL_WANDS, - SKILL_FISHING - }; - - const static uint32 item_armor_skills[MAX_ITEM_SUBCLASS_ARMOR] = - { - 0, SKILL_CLOTH, SKILL_LEATHER, SKILL_MAIL, SKILL_PLATE_MAIL, 0, SKILL_SHIELD, 0, 0, 0, 0 - }; - ItemTemplate const* proto = GetTemplate(); - - switch (proto->Class) - { - case ITEM_CLASS_WEAPON: - if (proto->SubClass >= MAX_ITEM_SUBCLASS_WEAPON) - return 0; - else - return item_weapon_skills[proto->SubClass]; - - case ITEM_CLASS_ARMOR: - if (proto->SubClass >= MAX_ITEM_SUBCLASS_ARMOR) - return 0; - else - return item_armor_skills[proto->SubClass]; - - default: - return 0; - } + return proto->GetSkill(); } uint32 Item::GetSpell() diff --git a/src/server/game/Entities/Item/Item.h b/src/server/game/Entities/Item/Item.h index 378d7f5e2e4..5e00a816cab 100644 --- a/src/server/game/Entities/Item/Item.h +++ b/src/server/game/Entities/Item/Item.h @@ -22,7 +22,7 @@ #include "Common.h" #include "Object.h" #include "LootMgr.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" #include "DatabaseEnv.h" class SpellInfo; @@ -203,7 +203,7 @@ enum ItemUpdateState bool ItemCanGoIntoBag(ItemTemplate const* proto, ItemTemplate const* pBagProto); -class Item : public Object +class TC_GAME_API Item : public Object { public: static Item* CreateItem(uint32 itemEntry, uint32 count, Player const* player = NULL); diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.h b/src/server/game/Entities/Item/ItemEnchantmentMgr.h index 2d5c27177b1..8ce9ae780fe 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.h +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.h @@ -21,8 +21,9 @@ #include "Common.h" -void LoadRandomEnchantmentsTable(); -uint32 GetItemEnchantMod(int32 entry); -uint32 GenerateEnchSuffixFactor(uint32 item_id); +TC_GAME_API void LoadRandomEnchantmentsTable(); +TC_GAME_API uint32 GetItemEnchantMod(int32 entry); +TC_GAME_API uint32 GenerateEnchSuffixFactor(uint32 item_id); + #endif diff --git a/src/server/game/Entities/Item/ItemTemplate.cpp b/src/server/game/Entities/Item/ItemTemplate.cpp new file mode 100644 index 00000000000..1a8bc2291ae --- /dev/null +++ b/src/server/game/Entities/Item/ItemTemplate.cpp @@ -0,0 +1,124 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "ItemTemplate.h" + +bool ItemTemplate::CanChangeEquipStateInCombat() const +{ + switch (InventoryType) + { + case INVTYPE_RELIC: + case INVTYPE_SHIELD: + case INVTYPE_HOLDABLE: + return true; + } + + switch (Class) + { + case ITEM_CLASS_WEAPON: + case ITEM_CLASS_PROJECTILE: + return true; + } + + return false; +} + + +float ItemTemplate::getDPS() const +{ + if (!Delay) + return 0.f; + + float temp = 0.f; + for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) + temp += Damage[i].DamageMin + Damage[i].DamageMax; + + return temp * 500.f / Delay; +} + +int32 ItemTemplate::getFeralBonus(int32 extraDPS /*= 0*/) const +{ + // 0x02A5F3 - is mask for Melee weapon from ItemSubClassMask.dbc + if (Class == ITEM_CLASS_WEAPON && (1 << SubClass) & 0x02A5F3) + { + int32 bonus = int32((extraDPS + getDPS()) * 14.0f) - 767; + if (bonus < 0) + return 0; + return bonus; + } + + return 0; +} + +float ItemTemplate::GetItemLevelIncludingQuality() const +{ + float itemLevel(ItemLevel); + switch (Quality) + { + case ITEM_QUALITY_POOR: + case ITEM_QUALITY_NORMAL: + case ITEM_QUALITY_UNCOMMON: + case ITEM_QUALITY_ARTIFACT: + case ITEM_QUALITY_HEIRLOOM: + itemLevel -= 13.f; // leaving this as a separate statement since we do not know the real behavior in this case + break; + case ITEM_QUALITY_RARE: + itemLevel -= 13.f; + break; + case ITEM_QUALITY_EPIC: + case ITEM_QUALITY_LEGENDARY: + default: + break; + } + + return std::max<float>(0.f, itemLevel); +} + +uint32 ItemTemplate::GetSkill() const +{ + static uint32 const itemWeaponSkills[MAX_ITEM_SUBCLASS_WEAPON] = + { + SKILL_AXES, SKILL_2H_AXES, SKILL_BOWS, SKILL_GUNS, SKILL_MACES, + SKILL_2H_MACES, SKILL_POLEARMS, SKILL_SWORDS, SKILL_2H_SWORDS, 0, + SKILL_STAVES, 0, 0, SKILL_FIST_WEAPONS, 0, + SKILL_DAGGERS, SKILL_THROWN, SKILL_ASSASSINATION, SKILL_CROSSBOWS, SKILL_WANDS, + SKILL_FISHING + }; + + static uint32 const itemArmorSkills[MAX_ITEM_SUBCLASS_ARMOR] = + { + 0, SKILL_CLOTH, SKILL_LEATHER, SKILL_MAIL, SKILL_PLATE_MAIL, 0, SKILL_SHIELD, 0, 0, 0, 0 + }; + + switch (Class) + { + case ITEM_CLASS_WEAPON: + if (SubClass >= MAX_ITEM_SUBCLASS_WEAPON) + return 0; + else + return itemWeaponSkills[SubClass]; + + case ITEM_CLASS_ARMOR: + if (SubClass >= MAX_ITEM_SUBCLASS_ARMOR) + return 0; + else + return itemArmorSkills[SubClass]; + + default: + return 0; + } +} diff --git a/src/server/game/Entities/Item/ItemPrototype.h b/src/server/game/Entities/Item/ItemTemplate.h index 48ef9e81016..0ff3f00a08b 100644 --- a/src/server/game/Entities/Item/ItemPrototype.h +++ b/src/server/game/Entities/Item/ItemTemplate.h @@ -107,20 +107,20 @@ enum ItemBondingType enum ItemProtoFlags { - ITEM_PROTO_FLAG_UNK1 = 0x00000001, // ? + ITEM_PROTO_FLAG_NO_PICKUP = 0x00000001, // ? ITEM_PROTO_FLAG_CONJURED = 0x00000002, // Conjured item - ITEM_PROTO_FLAG_OPENABLE = 0x00000004, // Item can be right clicked to open for loot + ITEM_PROTO_FLAG_HAS_LOOT = 0x00000004, // Item can be right clicked to open for loot ITEM_PROTO_FLAG_HEROIC = 0x00000008, // Makes green "Heroic" text appear on item ITEM_PROTO_FLAG_DEPRECATED = 0x00000010, // Cannot equip or use ITEM_PROTO_FLAG_INDESTRUCTIBLE = 0x00000020, // Item can not be destroyed, except by using spell (item can be reagent for spell) - ITEM_PROTO_FLAG_UNK2 = 0x00000040, // ? + ITEM_PROTO_FLAG_PLAYER_CAST = 0x00000040, // Item's spells are castable by players ITEM_PROTO_FLAG_NO_EQUIP_COOLDOWN = 0x00000080, // No default 30 seconds cooldown when equipped - ITEM_PROTO_FLAG_UNK3 = 0x00000100, // ? - ITEM_PROTO_FLAG_WRAPPER = 0x00000200, // Item can wrap other items - ITEM_PROTO_FLAG_UNK4 = 0x00000400, // ? - ITEM_PROTO_FLAG_PARTY_LOOT = 0x00000800, // Looting this item does not remove it from available loot + ITEM_PROTO_FLAG_INT_BONUS_INSTEAD = 0x00000100, // ? + ITEM_PROTO_FLAG_IS_WRAPPER = 0x00000200, // Item can wrap other items + ITEM_PROTO_FLAG_USES_RESOURCES = 0x00000400, // ? + ITEM_PROTO_FLAG_MULTI_DROP = 0x00000800, // Looting this item does not remove it from available loot ITEM_PROTO_FLAG_REFUNDABLE = 0x00001000, // Item can be returned to vendor for its original cost (extended cost) - ITEM_PROTO_FLAG_CHARTER = 0x00002000, // Item is guild or arena charter + ITEM_PROTO_FLAG_PETITION = 0x00002000, // Item is guild or arena charter ITEM_PROTO_FLAG_UNK5 = 0x00004000, // Only readable items have this (but not all) ITEM_PROTO_FLAG_UNK6 = 0x00008000, // ? ITEM_PROTO_FLAG_UNK7 = 0x00010000, // ? @@ -537,12 +537,7 @@ inline uint8 ItemSubClassToDurabilityMultiplierId(uint32 ItemClass, uint32 ItemS return 0; } -// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push, N), also any gcc version not support it at some platform -#if defined(__GNUC__) -#pragma pack(1) -#else #pragma pack(push, 1) -#endif struct _Damage { @@ -573,12 +568,7 @@ struct _Socket uint32 Content; }; -// GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some platform -#if defined(__GNUC__) -#pragma pack() -#else #pragma pack(pop) -#endif #define MAX_ITEM_PROTO_DAMAGES 2 // changed in 3.1.0 #define MAX_ITEM_PROTO_SOCKETS 3 @@ -664,25 +654,7 @@ struct ItemTemplate uint32 FlagsCu; // helpers - bool CanChangeEquipStateInCombat() const - { - switch (InventoryType) - { - case INVTYPE_RELIC: - case INVTYPE_SHIELD: - case INVTYPE_HOLDABLE: - return true; - } - - switch (Class) - { - case ITEM_CLASS_WEAPON: - case ITEM_CLASS_PROJECTILE: - return true; - } - - return false; - } + bool CanChangeEquipStateInCombat() const; bool IsCurrencyToken() const { return (BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) != 0; } @@ -691,51 +663,13 @@ struct ItemTemplate return (Stackable == 2147483647 || Stackable <= 0) ? uint32(0x7FFFFFFF-1) : uint32(Stackable); } - float getDPS() const - { - if (Delay == 0) - return 0; - float temp = 0; - for (int i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) - temp+=Damage[i].DamageMin + Damage[i].DamageMax; - return temp*500/Delay; - } + float getDPS() const; - int32 getFeralBonus(int32 extraDPS = 0) const - { - // 0x02A5F3 - is mask for Melee weapon from ItemSubClassMask.dbc - if (Class == ITEM_CLASS_WEAPON && (1<<SubClass)&0x02A5F3) - { - int32 bonus = int32((extraDPS + getDPS())*14.0f) - 767; - if (bonus < 0) - return 0; - return bonus; - } - return 0; - } + int32 getFeralBonus(int32 extraDPS = 0) const; - float GetItemLevelIncludingQuality() const - { - float itemLevel = (float)ItemLevel; - switch (Quality) - { - case ITEM_QUALITY_POOR: - case ITEM_QUALITY_NORMAL: - case ITEM_QUALITY_UNCOMMON: - case ITEM_QUALITY_ARTIFACT: - case ITEM_QUALITY_HEIRLOOM: - itemLevel -= 13; // leaving this as a separate statement since we do not know the real behavior in this case - break; - case ITEM_QUALITY_RARE: - itemLevel -= 13; - break; - case ITEM_QUALITY_EPIC: - case ITEM_QUALITY_LEGENDARY: - default: - break; - } - return std::max<float>(0.f, itemLevel); - } + float GetItemLevelIncludingQuality() const; + + uint32 GetSkill() const; bool IsPotion() const { return Class == ITEM_CLASS_CONSUMABLE && SubClass == ITEM_SUBCLASS_POTION; } bool IsWeaponVellum() const { return Class == ITEM_CLASS_TRADE_GOODS && SubClass == ITEM_SUBCLASS_WEAPON_ENCHANTMENT; } diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index 4877ff094e1..20b88c5e3a9 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -221,7 +221,10 @@ void Object::SendUpdateToPlayer(Player* player) UpdateData upd; WorldPacket packet; - BuildCreateUpdateBlockForPlayer(&upd, player); + if (player->HaveAtClient(this)) + BuildValuesUpdateBlockForPlayer(&upd, player); + else + BuildCreateUpdateBlockForPlayer(&upd, player); upd.BuildPacket(&packet); player->GetSession()->SendPacket(&packet); } @@ -477,7 +480,7 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 flags) const // 0x200 if (flags & UPDATEFLAG_ROTATION) - *data << int64(ToGameObject()->GetRotation()); + *data << int64(ToGameObject()->GetPackedWorldRotation()); } void Object::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) const @@ -925,6 +928,11 @@ bool Object::HasByteFlag(uint16 index, uint8 offset, uint8 flag) const return (((uint8*)&m_uint32Values[index])[offset] & flag) != 0; } +void Object::ApplyModByteFlag(uint16 index, uint8 offset, uint8 flag, bool apply) +{ + if (apply) SetByteFlag(index, offset, flag); else RemoveByteFlag(index, offset, flag); +} + void Object::SetFlag64(uint16 index, uint64 newFlag) { uint64 oldval = GetUInt64Value(index); @@ -1146,9 +1154,13 @@ bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const if (!IsInMap(obj)) return false; - float ox, oy, oz; - obj->GetPosition(ox, oy, oz); - return IsWithinLOS(ox, oy, oz); + float x, y, z; + if (obj->GetTypeId() == TYPEID_PLAYER) + obj->GetPosition(x, y, z); + else + obj->GetHitSpherePointFor(GetPosition(), x, y, z); + + return IsWithinLOS(x, y, z); } float WorldObject::GetDistance(const WorldObject* obj) const @@ -1232,11 +1244,36 @@ bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const VMAP::IVMapManager* vMapManager = VMAP::VMapFactory::createOrGetVMapManager(); return vMapManager->isInLineOfSight(GetMapId(), x, y, z+2.0f, ox, oy, oz+2.0f);*/ if (IsInWorld()) - return GetMap()->isInLineOfSight(GetPositionX(), GetPositionY(), GetPositionZ()+2.f, ox, oy, oz+2.f, GetPhaseMask()); + { + float x, y, z; + if (GetTypeId() == TYPEID_PLAYER) + GetPosition(x, y, z); + else + GetHitSpherePointFor({ ox, oy, oz }, x, y, z); + + return GetMap()->isInLineOfSight(x, y, z + 2.0f, ox, oy, oz + 2.0f, GetPhaseMask()); + } return true; } +Position WorldObject::GetHitSpherePointFor(Position const& dest) const +{ + G3D::Vector3 vThis(GetPositionX(), GetPositionY(), GetPositionZ()); + G3D::Vector3 vObj(dest.GetPositionX(), dest.GetPositionY(), dest.GetPositionZ()); + G3D::Vector3 contactPoint = vThis + (vObj - vThis).directionOrZero() * GetObjectSize(); + + return Position(contactPoint.x, contactPoint.y, contactPoint.z, GetAngle(contactPoint.x, contactPoint.y)); +} + +void WorldObject::GetHitSpherePointFor(Position const& dest, float& x, float& y, float& z) const +{ + Position pos = GetHitSpherePointFor(dest); + x = pos.GetPositionX(); + y = pos.GetPositionY(); + z = pos.GetPositionZ(); +} + bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const { float dx1 = GetPositionX() - obj1->GetPositionX(); @@ -1366,7 +1403,8 @@ void WorldObject::GetRandomPoint(const Position &pos, float distance, float &ran // angle to face `obj` to `this` float angle = (float)rand_norm()*static_cast<float>(2*M_PI); - float new_dist = (float)rand_norm()*static_cast<float>(distance); + float new_dist = (float)rand_norm() + (float)rand_norm(); + new_dist = distance * (new_dist > 1 ? new_dist - 2 : new_dist); rand_x = pos.m_positionX + new_dist * std::cos(angle); rand_y = pos.m_positionY + new_dist * std::sin(angle); @@ -1408,7 +1446,7 @@ void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const bool canSwim = ToCreature()->CanSwim(); float ground_z = z; float max_z = canSwim - ? GetMap()->GetWaterOrGroundLevel(x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)) + ? GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)) : ((ground_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z, true))); if (max_z > INVALID_HEIGHT) { @@ -1432,7 +1470,7 @@ void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const if (!ToPlayer()->CanFly()) { float ground_z = z; - float max_z = GetMap()->GetWaterOrGroundLevel(x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)); + float max_z = GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), x, y, z, &ground_z, !ToUnit()->HasAuraType(SPELL_AURA_WATER_WALK)); if (max_z > INVALID_HEIGHT) { if (z > max_z) @@ -1462,9 +1500,20 @@ void WorldObject::UpdateAllowedPositionZ(float x, float y, float &z) const float WorldObject::GetGridActivationRange() const { if (ToPlayer()) + { + if (ToPlayer()->GetCinematicMgr()->IsOnCinematic()) + return DEFAULT_VISIBILITY_INSTANCE; return GetMap()->GetVisibilityRange(); + } else if (ToCreature()) return ToCreature()->m_SightDistance; + else if (ToDynObject()) + { + if (isActiveObject()) + return GetMap()->GetVisibilityRange(); + else + return 0.0f; + } else return 0.0f; } @@ -1485,6 +1534,8 @@ float WorldObject::GetSightRange(const WorldObject* target) const { if (target && target->isActiveObject() && !target->ToPlayer()) return MAX_VISIBILITY_DISTANCE; + else if (ToPlayer()->GetCinematicMgr()->IsOnCinematic()) + return DEFAULT_VISIBILITY_INSTANCE; else return GetMap()->GetVisibilityRange(); } @@ -1494,6 +1545,11 @@ float WorldObject::GetSightRange(const WorldObject* target) const return SIGHT_RANGE_UNIT; } + if (ToDynObject() && isActiveObject()) + { + return GetMap()->GetVisibilityRange(); + } + return 0.0f; } @@ -1878,7 +1934,9 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert AddToMap(summon->ToCreature()); summon->InitSummon(); - //ObjectAccessor::UpdateObjectVisibility(summon); + // call MoveInLineOfSight for nearby creatures + Trinity::AIRelocationNotifier notifier(*summon); + summon->VisitNearbyObject(GetVisibilityRange(), notifier); return summon; } @@ -1923,7 +1981,7 @@ void WorldObject::ClearZoneScript() m_zoneScript = NULL; } -TempSummon* WorldObject::SummonCreature(uint32 entry, const Position &pos, TempSummonType spwtype, uint32 duration, uint32 /*vehId*/) const +TempSummon* WorldObject::SummonCreature(uint32 entry, Position const& pos, TempSummonType spwtype /*= TEMPSUMMON_MANUAL_DESPAWN*/, uint32 duration /*= 0*/, uint32 /*vehId = 0*/) const { if (Map* map = FindMap()) { @@ -1934,7 +1992,7 @@ TempSummon* WorldObject::SummonCreature(uint32 entry, const Position &pos, TempS } } - return NULL; + return nullptr; } TempSummon* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang /*= 0*/, TempSummonType spwtype /*= TEMPSUMMON_MANUAL_DESPAWN*/, uint32 despwtime /*= 0*/) const @@ -1944,29 +2002,30 @@ TempSummon* WorldObject::SummonCreature(uint32 id, float x, float y, float z, fl GetClosePoint(x, y, z, GetObjectSize()); ang = GetOrientation(); } + Position pos; pos.Relocate(x, y, z, ang); return SummonCreature(id, pos, spwtype, despwtime, 0); } -GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime) +GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime) { if (!IsInWorld()) - return NULL; + return nullptr; GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(entry); if (!goinfo) { TC_LOG_ERROR("sql.sql", "Gameobject template %u not found in database!", entry); - return NULL; + return nullptr; } Map* map = GetMap(); GameObject* go = new GameObject(); - if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, GetPhaseMask(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3, 100, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), entry, map, GetPhaseMask(), pos, rot, 255, GO_STATE_READY)) { delete go; - return NULL; + return nullptr; } go->SetRespawnTime(respawnTime); @@ -1979,6 +2038,18 @@ GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float return go; } +GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime) +{ + if (!x && !y && !z) + { + GetClosePoint(x, y, z, GetObjectSize()); + ang = GetOrientation(); + } + + Position pos(x, y, z, ang); + return SummonGameObject(entry, pos, rot, respawnTime); +} + Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint32 duration, CreatureAI* (*GetAI)(Creature*)) { TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; @@ -2010,7 +2081,10 @@ void WorldObject::SummonCreatureGroup(uint8 group, std::list<TempSummon*>* list std::vector<TempSummonData> const* data = sObjectMgr->GetSummonGroup(GetEntry(), GetTypeId() == TYPEID_GAMEOBJECT ? SUMMONER_TYPE_GAMEOBJECT : SUMMONER_TYPE_CREATURE, group); if (!data) + { + TC_LOG_WARN("scripts", "%s (%s) tried to summon non-existing summon group %u.", GetName().c_str(), GetGUID().ToString().c_str(), group); return; + } for (std::vector<TempSummonData>::const_iterator itr = data->begin(); itr != data->end(); ++itr) if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, itr->type, itr->time)) diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index 419044081e3..87b158ab81a 100644 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -90,7 +90,7 @@ class ZoneScript; typedef std::unordered_map<Player*, UpdateData> UpdateDataMapType; -class Object +class TC_GAME_API Object { public: virtual ~Object(); @@ -160,6 +160,7 @@ class Object void RemoveByteFlag(uint16 index, uint8 offset, uint8 newFlag); void ToggleByteFlag(uint16 index, uint8 offset, uint8 flag); bool HasByteFlag(uint16 index, uint8 offset, uint8 flag) const; + void ApplyModByteFlag(uint16 index, uint8 offset, uint8 flag, bool apply); void SetFlag64(uint16 index, uint64 newFlag); void RemoveFlag64(uint16 index, uint64 oldFlag); @@ -397,7 +398,7 @@ enum MapObjectCellMoveState MAP_OBJECT_CELL_MOVE_INACTIVE, //in move list but should not move }; -class MapObject +class TC_GAME_API MapObject { friend class Map; //map for moving creatures friend class ObjectGridLoader; //grid loader for loading creatures @@ -422,7 +423,7 @@ class MapObject } }; -class WorldObject : public Object, public WorldLocation +class TC_GAME_API WorldObject : public Object, public WorldLocation { protected: explicit WorldObject(bool isWorldObject); //note: here it means if it is in grid object list or world object list @@ -487,6 +488,8 @@ class WorldObject : public Object, public WorldLocation bool IsWithinDistInMap(WorldObject const* obj, float dist2compare, bool is3D = true) const; bool IsWithinLOS(float x, float y, float z) const; bool IsWithinLOSInMap(WorldObject const* obj) const; + Position GetHitSpherePointFor(Position const& dest) const; + void GetHitSpherePointFor(Position const& dest, float& x, float& y, float& z) const; bool GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D = true) const; bool IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D = true) const; bool IsInRange2d(float x, float y, float minRange, float maxRange) const; @@ -539,9 +542,10 @@ class WorldObject : public Object, public WorldLocation void ClearZoneScript(); ZoneScript* GetZoneScript() const { return m_zoneScript; } - TempSummon* SummonCreature(uint32 id, Position const &pos, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, uint32 vehId = 0) const; + TempSummon* SummonCreature(uint32 id, Position const& pos, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, uint32 vehId = 0) const; TempSummon* SummonCreature(uint32 id, float x, float y, float z, float ang = 0, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0) const; - GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime /* s */); + GameObject* SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime /* s */); + GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime /* s */); Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, CreatureAI* (*GetAI)(Creature*) = NULL); void SummonCreatureGroup(uint8 group, std::list<TempSummon*>* list = NULL); @@ -549,12 +553,17 @@ class WorldObject : public Object, public WorldLocation GameObject* FindNearestGameObject(uint32 entry, float range) const; GameObject* FindNearestGameObjectOfType(GameobjectTypes type, float range) const; - void GetGameObjectListWithEntryInGrid(std::list<GameObject*>& lList, uint32 uiEntry, float fMaxSearchRange) const; - void GetCreatureListWithEntryInGrid(std::list<Creature*>& lList, uint32 uiEntry, float fMaxSearchRange) const; + void GetGameObjectListWithEntryInGrid(std::list<GameObject*>& lList, uint32 uiEntry = 0, float fMaxSearchRange = 250.0f) const; + void GetCreatureListWithEntryInGrid(std::list<Creature*>& lList, uint32 uiEntry = 0, float fMaxSearchRange = 250.0f) const; void GetPlayerListInGrid(std::list<Player*>& lList, float fMaxSearchRange) const; void DestroyForNearbyPlayers(); virtual void UpdateObjectVisibility(bool forced = true); + virtual void UpdateObjectVisibilityOnCreate() + { + UpdateObjectVisibility(true); + } + void BuildUpdate(UpdateDataMapType&) override; void AddToObjectUpdate() override; @@ -578,14 +587,6 @@ class WorldObject : public Object, public WorldLocation template<class NOTIFIER> void VisitNearbyGridObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitGrid(GetPositionX(), GetPositionY(), radius, notifier); } template<class NOTIFIER> void VisitNearbyWorldObject(float const& radius, NOTIFIER& notifier) const { if (IsInWorld()) GetMap()->VisitWorld(GetPositionX(), GetPositionY(), radius, notifier); } -#ifdef MAP_BASED_RAND_GEN - int32 irand(int32 min, int32 max) const { return int32 (GetMap()->mtRand.randInt(max - min)) + min; } - uint32 urand(uint32 min, uint32 max) const { return GetMap()->mtRand.randInt(max - min) + min;} - int32 rand32() const { return GetMap()->mtRand.randInt();} - double rand_norm() const { return GetMap()->mtRand.randExc();} - double rand_chance() const { return GetMap()->mtRand.randExc(100.0);} -#endif - uint32 LastUsedScriptID; // Transports diff --git a/src/server/game/Entities/Object/ObjectGuid.cpp b/src/server/game/Entities/Object/ObjectGuid.cpp index 3e2bd000b6e..2fb766c5201 100644 --- a/src/server/game/Entities/Object/ObjectGuid.cpp +++ b/src/server/game/Entities/Object/ObjectGuid.cpp @@ -95,4 +95,19 @@ void ObjectGuidGeneratorBase::HandleCounterOverflow(HighGuid high) { TC_LOG_ERROR("misc", "%s guid overflow!! Can't continue, shutting down server. ", ObjectGuid::GetTypeName(high)); World::StopNow(ERROR_EXIT_CODE); -}
\ No newline at end of file +} + +#define GUID_TRAIT_INSTANTIATE_GUID( HIGH_GUID ) \ + template class TC_GAME_API ObjectGuidGenerator< HIGH_GUID >; + +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Container) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Player) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::GameObject) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Transport) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Unit) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Pet) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Vehicle) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::DynamicObject) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Mo_Transport) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Instance) +GUID_TRAIT_INSTANTIATE_GUID(HighGuid::Group) diff --git a/src/server/game/Entities/Object/ObjectGuid.h b/src/server/game/Entities/Object/ObjectGuid.h index 44644421567..71c66622790 100644 --- a/src/server/game/Entities/Object/ObjectGuid.h +++ b/src/server/game/Entities/Object/ObjectGuid.h @@ -111,7 +111,7 @@ struct PackedGuidReader ObjectGuid* GuidPtr; }; -class ObjectGuid +class TC_GAME_API ObjectGuid { public: static ObjectGuid const Empty; @@ -252,9 +252,9 @@ typedef std::unordered_set<ObjectGuid> GuidUnorderedSet; // minimum buffer size for packed guid is 9 bytes #define PACKED_GUID_MIN_BUFFER_SIZE 9 -class PackedGuid +class TC_GAME_API PackedGuid { - friend ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); + friend TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); public: explicit PackedGuid() : _packedGuid(PACKED_GUID_MIN_BUFFER_SIZE) { _packedGuid.appendPackGUID(0); } @@ -270,8 +270,7 @@ class PackedGuid ByteBuffer _packedGuid; }; - -class ObjectGuidGeneratorBase +class TC_GAME_API ObjectGuidGeneratorBase { public: ObjectGuidGeneratorBase(ObjectGuid::LowType start = 1) : _nextGuid(start) { } @@ -286,7 +285,7 @@ protected: }; template<HighGuid high> -class ObjectGuidGenerator : public ObjectGuidGeneratorBase +class TC_GAME_API ObjectGuidGenerator : public ObjectGuidGeneratorBase { public: explicit ObjectGuidGenerator(ObjectGuid::LowType start = 1) : ObjectGuidGeneratorBase(start) { } @@ -299,11 +298,11 @@ public: } }; -ByteBuffer& operator<<(ByteBuffer& buf, ObjectGuid const& guid); -ByteBuffer& operator>>(ByteBuffer& buf, ObjectGuid& guid); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, ObjectGuid const& guid); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, ObjectGuid& guid); -ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); -ByteBuffer& operator>>(ByteBuffer& buf, PackedGuidReader const& guid); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, PackedGuidReader const& guid); inline PackedGuid ObjectGuid::WriteAsPacked() const { return PackedGuid(*this); } diff --git a/src/server/game/Entities/Object/ObjectPosSelector.h b/src/server/game/Entities/Object/ObjectPosSelector.h index 26a23678009..84c694abf08 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.h +++ b/src/server/game/Entities/Object/ObjectPosSelector.h @@ -30,7 +30,7 @@ inline UsedPosType operator ~(UsedPosType uptype) return uptype==USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS; } -struct ObjectPosSelector +struct TC_GAME_API ObjectPosSelector { struct UsedPos { diff --git a/src/server/game/Entities/Object/Position.h b/src/server/game/Entities/Object/Position.h index 18d356c28d4..6325cc51fe2 100644 --- a/src/server/game/Entities/Object/Position.h +++ b/src/server/game/Entities/Object/Position.h @@ -22,7 +22,7 @@ class ByteBuffer; -struct Position +struct TC_GAME_API Position { Position(float x = 0, float y = 0, float z = 0, float o = 0) : m_positionX(x), m_positionY(y), m_positionZ(z), m_orientation(NormalizeOrientation(o)) { } @@ -216,11 +216,11 @@ public: } }; -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); #endif // Trinity_game_Position_h__ diff --git a/src/server/game/Entities/Object/Updates/UpdateFieldFlags.h b/src/server/game/Entities/Object/Updates/UpdateFieldFlags.h index 0b4e59f4f9b..8208a5e9894 100644 --- a/src/server/game/Entities/Object/Updates/UpdateFieldFlags.h +++ b/src/server/game/Entities/Object/Updates/UpdateFieldFlags.h @@ -35,10 +35,10 @@ enum UpdatefieldFlags UF_FLAG_DYNAMIC = 0x100 }; -extern uint32 ItemUpdateFieldFlags[CONTAINER_END]; -extern uint32 UnitUpdateFieldFlags[PLAYER_END]; -extern uint32 GameObjectUpdateFieldFlags[GAMEOBJECT_END]; -extern uint32 DynamicObjectUpdateFieldFlags[DYNAMICOBJECT_END]; -extern uint32 CorpseUpdateFieldFlags[CORPSE_END]; +TC_GAME_API extern uint32 ItemUpdateFieldFlags[CONTAINER_END]; +TC_GAME_API extern uint32 UnitUpdateFieldFlags[PLAYER_END]; +TC_GAME_API extern uint32 GameObjectUpdateFieldFlags[GAMEOBJECT_END]; +TC_GAME_API extern uint32 DynamicObjectUpdateFieldFlags[DYNAMICOBJECT_END]; +TC_GAME_API extern uint32 CorpseUpdateFieldFlags[CORPSE_END]; #endif // _UPDATEFIELDFLAGS_H diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index 0da63c5e500..482fcb315f2 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -213,12 +213,14 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c case SUMMON_PET: petlevel = owner->getLevel(); - SetUInt32Value(UNIT_FIELD_BYTES_0, 0x800); // class = mage + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, uint8(CLASS_MAGE)); SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); // this enables popup window (pet dismiss, cancel) break; case HUNTER_PET: - SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100); // class = warrior, gender = none, power = focus + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, CLASS_WARRIOR); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, GENDER_NONE); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE, POWER_FOCUS); SetSheath(SHEATH_STATE_MELEE); SetByteFlag(UNIT_FIELD_BYTES_2, 2, fields[9].GetBool() ? UNIT_CAN_BE_ABANDONED : UNIT_CAN_BE_RENAMED | UNIT_CAN_BE_ABANDONED); @@ -226,7 +228,6 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c // this enables popup window (pet abandon, cancel) SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); SetPower(POWER_HAPPINESS, fields[12].GetUInt32()); - setPowerType(POWER_FOCUS); break; default: if (!IsPetGhoul()) @@ -328,6 +329,9 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c _LoadSpellCooldowns(); LearnPetPassives(); InitLevelupSpellsForLevel(); + if (map->IsBattleArena()) + RemoveArenaAuras(); + CastPetAuras(current); } @@ -747,7 +751,7 @@ void Pet::GivePetLevel(uint8 level) if (!level || level == getLevel()) return; - if (getPetType()==HUNTER_PET) + if (getPetType() == HUNTER_PET) { SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, uint32(sObjectMgr->GetXPForLevel(level)*PET_XP_FACTOR)); @@ -822,7 +826,9 @@ bool Pet::CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phas if (cinfo->type == CREATURE_TYPE_BEAST) { - SetUInt32Value(UNIT_FIELD_BYTES_0, 0x02020100); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, CLASS_WARRIOR); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, GENDER_NONE); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE, POWER_FOCUS); SetSheath(SHEATH_STATE_MELEE); SetByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED | UNIT_CAN_BE_ABANDONED); } diff --git a/src/server/game/Entities/Pet/Pet.h b/src/server/game/Entities/Pet/Pet.h index b0863a371e6..3a65fb44e04 100644 --- a/src/server/game/Entities/Pet/Pet.h +++ b/src/server/game/Entities/Pet/Pet.h @@ -37,7 +37,7 @@ typedef std::vector<uint32> AutoSpellList; class Player; -class Pet : public Guardian +class TC_GAME_API Pet : public Guardian { public: explicit Pet(Player* owner, PetType type = MAX_PET_TYPE); diff --git a/src/server/game/Entities/Player/CinematicMgr.cpp b/src/server/game/Entities/Player/CinematicMgr.cpp new file mode 100644 index 00000000000..cc5a62300ad --- /dev/null +++ b/src/server/game/Entities/Player/CinematicMgr.cpp @@ -0,0 +1,174 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include "CinematicMgr.h" +#include "Creature.h" +#include "Player.h" +#include "TemporarySummon.h" + +CinematicMgr::CinematicMgr(Player* playerref) +{ + player = playerref; + m_cinematicDiff = 0; + m_lastCinematicCheck = 0; + m_activeCinematicCameraId = 0; + m_cinematicLength = 0; + m_cinematicCamera = nullptr; + m_remoteSightPosition = Position(0.0f, 0.0f, 0.0f); + m_CinematicObject = nullptr; +} + +CinematicMgr::~CinematicMgr() +{ + if (m_cinematicCamera && m_activeCinematicCameraId) + EndCinematic(); +} + +void CinematicMgr::BeginCinematic() +{ + // Sanity check for active camera set + if (m_activeCinematicCameraId == 0) + return; + + auto itr = sFlyByCameraStore.find(m_activeCinematicCameraId); + if (itr != sFlyByCameraStore.end()) + { + // Initialize diff, and set camera + m_cinematicDiff = 0; + m_cinematicCamera = &itr->second; + + auto camitr = m_cinematicCamera->begin(); + if (camitr != m_cinematicCamera->end()) + { + Position pos(camitr->locations.x, camitr->locations.y, camitr->locations.z, camitr->locations.w); + if (!pos.IsPositionValid()) + return; + + player->GetMap()->LoadGrid(camitr->locations.x, camitr->locations.y); + m_CinematicObject = player->SummonCreature(VISUAL_WAYPOINT, pos.m_positionX, pos.m_positionY, pos.m_positionZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 5 * MINUTE * IN_MILLISECONDS); + if (m_CinematicObject) + { + m_CinematicObject->setActive(true); + player->SetViewpoint(m_CinematicObject, true); + } + + // Get cinematic length + FlyByCameraCollection::const_reverse_iterator camrevitr = m_cinematicCamera->rbegin(); + if (camrevitr != m_cinematicCamera->rend()) + m_cinematicLength = camrevitr->timeStamp; + else + m_cinematicLength = 0; + } + } +} + +void CinematicMgr::EndCinematic() +{ + if (m_activeCinematicCameraId == 0) + return; + + m_cinematicDiff = 0; + m_cinematicCamera = nullptr; + m_activeCinematicCameraId = 0; + if (m_CinematicObject) + { + if (WorldObject* vpObject = player->GetViewpoint()) + if (vpObject == m_CinematicObject) + player->SetViewpoint(m_CinematicObject, false); + + m_CinematicObject->AddObjectToRemoveList(); + } +} + +void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) +{ + if (m_activeCinematicCameraId == 0 || !m_cinematicCamera || m_cinematicCamera->size() == 0) + return; + + Position lastPosition; + uint32 lastTimestamp = 0; + Position nextPosition; + uint32 nextTimestamp = 0; + + // Obtain direction of travel + for (FlyByCamera cam : *m_cinematicCamera) + { + if (cam.timeStamp > m_cinematicDiff) + { + nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextTimestamp = cam.timeStamp; + break; + } + lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastTimestamp = cam.timeStamp; + } + float angle = lastPosition.GetAngle(&nextPosition); + angle -= lastPosition.GetOrientation(); + if (angle < 0) + angle += 2 * float(M_PI); + + // Look for position around 2 second ahead of us. + int32 workDiff = m_cinematicDiff; + + // Modify result based on camera direction (Humans for example, have the camera point behind) + workDiff += static_cast<int32>(float(CINEMATIC_LOOKAHEAD) * cos(angle)); + + // Get an iterator to the last entry in the cameras, to make sure we don't go beyond the end + FlyByCameraCollection::const_reverse_iterator endItr = m_cinematicCamera->rbegin(); + if (endItr != m_cinematicCamera->rend() && workDiff > static_cast<int32>(endItr->timeStamp)) + workDiff = endItr->timeStamp; + + // Never try to go back in time before the start of cinematic! + if (workDiff < 0) + workDiff = m_cinematicDiff; + + // Obtain the previous and next waypoint based on timestamp + for (FlyByCamera cam : *m_cinematicCamera) + { + if (static_cast<int32>(cam.timeStamp) >= workDiff) + { + nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextTimestamp = cam.timeStamp; + break; + } + lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastTimestamp = cam.timeStamp; + } + + // Never try to go beyond the end of the cinematic + if (workDiff > static_cast<int32>(nextTimestamp)) + workDiff = static_cast<int32>(nextTimestamp); + + // Interpolate the position for this moment in time (or the adjusted moment in time) + uint32 timeDiff = nextTimestamp - lastTimestamp; + uint32 interDiff = workDiff - lastTimestamp; + float xDiff = nextPosition.m_positionX - lastPosition.m_positionX; + float yDiff = nextPosition.m_positionY - lastPosition.m_positionY; + float zDiff = nextPosition.m_positionZ - lastPosition.m_positionZ; + Position interPosition(lastPosition.m_positionX + (xDiff * (float(interDiff) / float(timeDiff))), lastPosition.m_positionY + + (yDiff * (float(interDiff) / float(timeDiff))), lastPosition.m_positionZ + (zDiff * (float(interDiff) / float(timeDiff)))); + + // Advance (at speed) to this position. The remote sight object is used + // to send update information to player in cinematic + if (m_CinematicObject && interPosition.IsPositionValid()) + m_CinematicObject->MonsterMoveWithSpeed(interPosition.m_positionX, interPosition.m_positionY, interPosition.m_positionZ, 500.0f, false, true); + + // If we never received an end packet 10 seconds after the final timestamp then force an end + if (m_cinematicDiff > m_cinematicLength + 10 * IN_MILLISECONDS) + EndCinematic(); +} diff --git a/src/server/game/Entities/Player/CinematicMgr.h b/src/server/game/Entities/Player/CinematicMgr.h new file mode 100644 index 00000000000..ab067afa042 --- /dev/null +++ b/src/server/game/Entities/Player/CinematicMgr.h @@ -0,0 +1,60 @@ +/* +* Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> +* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef CinematicMgr_h__ +#define CinematicMgr_h__ + +#include "Define.h" +#include "Object.h" +#include "M2Stores.h" + +#define CINEMATIC_LOOKAHEAD (2 * IN_MILLISECONDS) +#define CINEMATIC_UPDATEDIFF 500 + +class Player; + +class TC_GAME_API CinematicMgr +{ + friend class Player; +public: + explicit CinematicMgr(Player* playerref); + ~CinematicMgr(); + + // Cinematic camera data and remote sight functions + uint32 GetActiveCinematicCamera() const { return m_activeCinematicCameraId; } + void SetActiveCinematicCamera(uint32 cinematicCameraId = 0) { m_activeCinematicCameraId = cinematicCameraId; } + bool IsOnCinematic() const { return (m_cinematicCamera != nullptr); } + void BeginCinematic(); + void EndCinematic(); + void UpdateCinematicLocation(uint32 diff); + +private: + // Remote location information + Player* player; + +protected: + uint32 m_cinematicDiff; + uint32 m_lastCinematicCheck; + uint32 m_activeCinematicCameraId; + uint32 m_cinematicLength; + FlyByCameraCollection* m_cinematicCamera; + Position m_remoteSightPosition; + TempSummon* m_CinematicObject; +}; + +#endif
\ No newline at end of file diff --git a/src/server/game/Entities/Player/KillRewarder.h b/src/server/game/Entities/Player/KillRewarder.h index 08530de900c..210e5ff0246 100644 --- a/src/server/game/Entities/Player/KillRewarder.h +++ b/src/server/game/Entities/Player/KillRewarder.h @@ -24,7 +24,7 @@ class Player; class Unit; class Group; -class KillRewarder +class TC_GAME_API KillRewarder { public: KillRewarder(Player* killer, Unit* victim, bool isBattleGround); diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index c7f674ec72c..bc95ea1107e 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -213,7 +213,7 @@ void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) if (all) { for (uint8 i = 0; i < TaxiMaskSize; ++i) - data << uint32(sTaxiNodesMask[i]); // all existed nodes + data << uint32(sTaxiNodesMask[i]); // all existing nodes } else { @@ -306,7 +306,7 @@ Player::Player(WorldSession* session): Unit(true) m_ExtraFlags = 0; - m_spellModTakingSpell = NULL; + m_spellModTakingSpell = nullptr; //m_pad = 0; // players always accept @@ -332,19 +332,17 @@ Player::Player(WorldSession* session): Unit(true) m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE); - clearResurrectRequestData(); - memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT); - m_social = NULL; + m_social = nullptr; // group is initialized in the reference constructor - SetGroupInvite(NULL); + SetGroupInvite(nullptr); m_groupUpdateMask = 0; m_auraRaidUpdateMask = 0; m_bPassOnGroupLoot = false; - duel = NULL; + duel = nullptr; m_GuildIdInvited = 0; m_ArenaTeamIdInvited = 0; @@ -359,7 +357,7 @@ Player::Player(WorldSession* session): Unit(true) m_bHasDelayedTeleport = false; m_teleport_options = 0; - m_trade = NULL; + m_trade = nullptr; m_cinematic = 0; @@ -394,7 +392,7 @@ Player::Player(WorldSession* session): Unit(true) m_bgBattlegroundQueueID[j].invitedToInstance = 0; } - m_logintime = time(NULL); + m_logintime = time(nullptr); m_Last_tick = m_logintime; m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; @@ -470,27 +468,17 @@ Player::Player(WorldSession* session): Unit(true) m_spellPenetrationItemMod = 0; // Honor System - m_lastHonorUpdateTime = time(NULL); + m_lastHonorUpdateTime = time(nullptr); m_IsBGRandomWinner = false; // Player summoning m_summon_expire = 0; - m_summon_mapid = 0; - m_summon_x = 0.0f; - m_summon_y = 0.0f; - m_summon_z = 0.0f; m_mover = this; m_movedPlayer = this; m_seer = this; - m_recallMap = 0; - m_recallX = 0; - m_recallY = 0; - m_recallZ = 0; - m_recallO = 0; - m_homebindMapId = 0; m_homebindAreaId = 0; m_homebindX = 0; @@ -499,11 +487,11 @@ Player::Player(WorldSession* session): Unit(true) m_contestedPvPTimer = 0; - m_declinedname = NULL; + m_declinedname = nullptr; m_isActive = true; - m_runes = NULL; + m_runes = nullptr; m_lastFallTime = 0; m_lastFallZ = 0; @@ -537,13 +525,16 @@ Player::Player(WorldSession* session): Unit(true) _activeCheats = CHEAT_NONE; healthBeforeDuel = 0; manaBeforeDuel = 0; + + _cinematicMgr = new CinematicMgr(this); + m_achievementMgr = new AchievementMgr(this); m_reputationMgr = new ReputationMgr(this); } Player::~Player() { - // it must be unloaded already in PlayerLogout and accessed only for loggined player + // it must be unloaded already in PlayerLogout and accessed only for logged in player //m_social = NULL; // Note: buy back item already deleted from DB when player was saved @@ -576,6 +567,7 @@ Player::~Player() delete m_runes; delete m_achievementMgr; delete m_reputationMgr; + delete _cinematicMgr; sWorld->DecreasePlayerCount(); } @@ -605,20 +597,20 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo PlayerInfo const* info = sObjectMgr->GetPlayerInfo(createInfo->Race, createInfo->Class); if (!info) { - TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid race/class pair (%u/%u) - refusing to do so.", + TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking attempt: Account %u tried to create a character named '%s' with an invalid race/class pair (%u/%u) - refusing to do so.", GetSession()->GetAccountId(), m_name.c_str(), createInfo->Race, createInfo->Class); return false; } for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++) - m_items[i] = NULL; + m_items[i] = nullptr; Relocate(info->positionX, info->positionY, info->positionZ, info->orientation); ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(createInfo->Class); if (!cEntry) { - TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid character class (%u) - refusing to do so (wrong DBC-files?)", + TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking attempt: Account %u tried to create a character named '%s' with an invalid character class (%u) - refusing to do so (wrong DBC-files?)", GetSession()->GetAccountId(), m_name.c_str(), createInfo->Class); return false; } @@ -633,21 +625,22 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo if (!IsValidGender(createInfo->Gender)) { - TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid gender (%u) - refusing to do so", + TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking attempt: Account %u tried to create a character named '%s' with an invalid gender (%u) - refusing to do so", GetSession()->GetAccountId(), m_name.c_str(), createInfo->Gender); return false; } if (!ValidateAppearance(createInfo->Race, createInfo->Class, createInfo->Gender, createInfo->HairStyle, createInfo->HairColor, createInfo->Face, createInfo->FacialHair, createInfo->Skin, true)) { - TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with invalid appearance attributes - refusing to do so", + TC_LOG_ERROR("entities.player", "Player::Create: Possible hacking attempt: Account %u tried to create a character named '%s' with invalid appearance attributes - refusing to do so", GetSession()->GetAccountId(), m_name.c_str()); return false; } - uint32 RaceClassGender = (createInfo->Race) | (createInfo->Class << 8) | (createInfo->Gender << 16); - - SetUInt32Value(UNIT_FIELD_BYTES_0, (RaceClassGender | (powertype << 24))); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_RACE, createInfo->Race); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, createInfo->Class); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, createInfo->Gender); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE, powertype); InitDisplayIds(); if (sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP) { @@ -660,13 +653,14 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1)); // -1 is default value - SetUInt32Value(PLAYER_BYTES, (createInfo->Skin | (createInfo->Face << 8) | (createInfo->HairStyle << 16) | (createInfo->HairColor << 24))); - SetUInt32Value(PLAYER_BYTES_2, (createInfo->FacialHair | - (0x00 << 8) | - (0x00 << 16) | - (((GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED) << 24))); - SetByteValue(PLAYER_BYTES_3, 0, createInfo->Gender); - SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1) + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID, createInfo->Skin); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID, createInfo->Face); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID, createInfo->HairStyle); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID, createInfo->HairColor); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE, createInfo->FacialHair); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE, (GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER, createInfo->Gender); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_ARENA_FACTION, 0); SetUInt32Value(PLAYER_GUILDID, 0); SetUInt32Value(PLAYER_GUILDRANK, 0); @@ -752,7 +746,7 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo } // Played time - m_Last_tick = time(NULL); + m_Last_tick = time(nullptr); m_Played_time[PLAYED_TIME_TOTAL] = 0; m_Played_time[PLAYED_TIME_LEVEL] = 0; @@ -851,7 +845,7 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo if (msg == EQUIP_ERR_OK) { RemoveItem(INVENTORY_SLOT_BAG_0, i, true); - pItem = StoreItem(sDest, pItem, true); + StoreItem(sDest, pItem, true); } // if this is ammo then use it @@ -868,7 +862,8 @@ bool Player::Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: Creating initial item, itemId = %u, count = %u", titem_id, titem_amount); + TC_LOG_DEBUG("entities.player.items", "Player::StoreNewItemInBestSlots: Player '%s' (%s) creates initial item (ItemID: %u, Count: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), titem_id, titem_amount); // attempt equip by one while (titem_amount > 0) @@ -897,7 +892,8 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) } // item can't be added - TC_LOG_ERROR("entities.player.items", "STORAGE: Can't equip or store initial item %u for race %u class %u, error msg = %u", titem_id, getRace(), getClass(), msg); + TC_LOG_ERROR("entities.player.items", "Player::StoreNewItemInBestSlots: Player '%s' (%s) can't equip or store initial item (ItemID: %u, Race: %u, Class: %u, InventoryResult: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), titem_id, getRace(), getClass(), msg); return false; } @@ -927,10 +923,10 @@ void Player::StopMirrorTimer(MirrorTimerType Type) GetSession()->SendPacket(&data); } -bool Player::IsImmuneToEnvironmentalDamage() +bool Player::IsImmuneToEnvironmentalDamage() const { // check for GM and death state included in isAttackableByAOE - return (!isTargetableForAttack(false)); + return !isTargetableForAttack(false); } uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) @@ -958,13 +954,14 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) data << uint32(resist); SendMessageToSet(&data, true); - uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + uint32 final_damage = DealDamage(this, damage, nullptr, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); if (!IsAlive()) { - if (type == DAMAGE_FALL) // DealDamage not apply item durability loss at self damage + if (type == DAMAGE_FALL) // DealDamage does not apply item durability loss from self-induced damage. { - TC_LOG_DEBUG("entities.player", "We are fall to death, loosing 10 percents durability"); + TC_LOG_DEBUG("entities.player", "Player::EnvironmentalDamage: Player '%s' (%s) fall to death, losing 10%% durability", + GetName().c_str(), GetGUID().ToString().c_str()); DurabilityLossAll(0.10f, false); // durability lost message WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0); @@ -977,7 +974,7 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) return final_damage; } -int32 Player::getMaxTimer(MirrorTimerType timer) +int32 Player::getMaxTimer(MirrorTimerType timer) const { switch (timer) { @@ -1018,7 +1015,7 @@ void Player::StopMirrorTimers() StopMirrorTimer(FIRE_TIMER); } -bool Player::IsMirrorTimerActive(MirrorTimerType type) +bool Player::IsMirrorTimerActive(MirrorTimerType type) const { return m_MirrorTimer[type] == getMaxTimer(type); } @@ -1178,7 +1175,7 @@ void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/) m_invisibilityDetect.DelFlag(INVISIBILITY_DRUNK); uint32 newDrunkenState = Player::GetDrunkenstateByValue(newDrunkValue); - SetByteValue(PLAYER_BYTES_3, 1, newDrunkValue); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION, newDrunkValue); UpdateObjectVisibility(); if (!isSobering) @@ -1200,7 +1197,7 @@ void Player::Update(uint32 p_time) return; // undelivered mail - if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL)) + if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(nullptr)) { SendNewMail(); ++unReadMails; @@ -1216,8 +1213,17 @@ void Player::Update(uint32 p_time) { //TC_LOG_FATAL("entities.player", "Player has m_pad %u during update!", m_pad); //if (m_spellModTakingSpell) - TC_LOG_FATAL("spells", "Player has m_spellModTakingSpell %u during update!", m_spellModTakingSpell->m_spellInfo->Id); - m_spellModTakingSpell = NULL; + TC_LOG_FATAL("spells", "Player::Update: Player '%s' (%s) has m_spellModTakingSpell (SpellID: %u) during update!", + GetName().c_str(), GetGUID().ToString().c_str(), m_spellModTakingSpell->m_spellInfo->Id); + m_spellModTakingSpell = nullptr; + } + + // Update cinematic location, if 500ms have passed and we're doing a cinematic now. + _cinematicMgr->m_cinematicDiff += p_time; + if (_cinematicMgr->m_cinematicCamera && _cinematicMgr->m_activeCinematicCameraId && GetMSTimeDiffToNow(_cinematicMgr->m_lastCinematicCheck) > CINEMATIC_UPDATEDIFF) + { + _cinematicMgr->m_lastCinematicCheck = getMSTime(); + _cinematicMgr->UpdateCinematicLocation(p_time); } //used to implement delayed far teleports @@ -1225,7 +1231,7 @@ void Player::Update(uint32 p_time) Unit::Update(p_time); SetCanDelayTeleport(false); - time_t now = time(NULL); + time_t now = time(nullptr); UpdatePvPFlag(now); @@ -1237,13 +1243,14 @@ void Player::Update(uint32 p_time) UpdateAfkReport(now); - if (IsCharmed()) - if (Unit* charmer = GetCharmer()) - if (charmer->GetTypeId() == TYPEID_UNIT && charmer->IsAlive()) - UpdateCharmedAI(); - - if (GetAI() && IsAIEnabled) + if (IsAIEnabled && GetAI()) GetAI()->UpdateAI(p_time); + else if (NeedChangeAI) + { + UpdateCharmAI(); + NeedChangeAI = false; + IsAIEnabled = (GetAI() != nullptr); + } // Update items that have just a limited lifetime if (now > m_Last_tick) @@ -1441,7 +1448,7 @@ void Player::Update(uint32 p_time) { // m_nextSave reset in SaveToDB call SaveToDB(); - TC_LOG_DEBUG("entities.player", "Player '%s' (GUID: %u) saved", GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player", "Player::Update: Player '%s' (%s) saved", GetName().c_str(), GetGUID().ToString().c_str()); } else m_nextSave -= p_time; @@ -1551,7 +1558,7 @@ void Player::setDeathState(DeathState s) { if (!cur) { - TC_LOG_ERROR("entities.player", "setDeathState: attempt to kill a dead player %s(%d)", GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::setDeathState: Attempt to kill a dead player '%s' (%s)", GetName().c_str(), GetGUID().ToString().c_str()); return; } @@ -1560,10 +1567,10 @@ void Player::setDeathState(DeathState s) // lost combo points at any target (targeted combo points clear in Unit::setDeathState) ClearComboPoints(); - clearResurrectRequestData(); + ClearResurrectRequestData(); //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD) - RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); // save value before aura remove in Unit::setDeathState ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL); @@ -1592,12 +1599,14 @@ void Player::setDeathState(DeathState s) bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) { - // 0 1 2 3 4 5 6 7 - // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, " - // 8 9 10 11 12 13 14 - // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, " - // 15 16 17 18 19 20 21 - // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_banned.guid, character_declinedname.genitive " + // 0 1 2 3 4 5 6 7 + // SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.skin, characters.face, characters.hairStyle, + // 8 9 10 11 12 13 14 15 + // characters.hairColor, characters.facialStyle, characters.level, characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, + // 16 17 18 19 20 21 22 + // guild_member.guildid, characters.playerFlags, characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, + // 23 24 + // character_banned.guid, character_declinedname.genitive Field* fields = result->Fetch(); @@ -1624,12 +1633,15 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) *data << uint8(plrClass); // class *data << uint8(gender); // gender - uint32 playerBytes = fields[5].GetUInt32(); - uint32 playerBytes2 = fields[6].GetUInt32(); + uint8 skin = fields[5].GetUInt8(); + uint8 face = fields[6].GetUInt8(); + uint8 hairStyle = fields[7].GetUInt8(); + uint8 hairColor = fields[8].GetUInt8(); + uint8 facialStyle = fields[9].GetUInt8(); - uint16 atLoginFlags = fields[15].GetUInt16(); + uint16 atLoginFlags = fields[18].GetUInt16(); - if (!ValidateAppearance(uint8(plrRace), uint8(plrClass), gender, uint8(playerBytes >> 16), uint8(playerBytes >> 24), uint8(playerBytes >> 8), uint8(playerBytes2), uint8(playerBytes))) + if (!ValidateAppearance(uint8(plrRace), uint8(plrClass), gender, hairStyle, hairColor, face, facialStyle, skin)) { TC_LOG_ERROR("entities.player.loading", "Player %u has wrong Appearance values (Hair/Skin/Color), forcing recustomize", guid); @@ -1643,25 +1655,24 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) } } - *data << uint8(playerBytes); // skin - *data << uint8(playerBytes >> 8); // face - *data << uint8(playerBytes >> 16); // hair style - *data << uint8(playerBytes >> 24); // hair color - - *data << uint8(playerBytes2 & 0xFF); // facial hair + *data << uint8(skin); + *data << uint8(face); + *data << uint8(hairStyle); + *data << uint8(hairColor); + *data << uint8(facialStyle); - *data << uint8(fields[7].GetUInt8()); // level - *data << uint32(fields[8].GetUInt16()); // zone - *data << uint32(fields[9].GetUInt16()); // map + *data << uint8(fields[10].GetUInt8()); // level + *data << uint32(fields[11].GetUInt16()); // zone + *data << uint32(fields[12].GetUInt16()); // map - *data << fields[10].GetFloat(); // x - *data << fields[11].GetFloat(); // y - *data << fields[12].GetFloat(); // z + *data << fields[13].GetFloat(); // x + *data << fields[14].GetFloat(); // y + *data << fields[15].GetFloat(); // z - *data << uint32(fields[13].GetUInt32()); // guild id + *data << uint32(fields[16].GetUInt32()); // guild id uint32 charFlags = 0; - uint32 playerFlags = fields[14].GetUInt32(); + uint32 playerFlags = fields[17].GetUInt32(); if (atLoginFlags & AT_LOGIN_RESURRECT) playerFlags &= ~PLAYER_FLAGS_GHOST; if (playerFlags & PLAYER_FLAGS_HIDE_HELM) @@ -1672,11 +1683,11 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) charFlags |= CHARACTER_FLAG_GHOST; if (atLoginFlags & AT_LOGIN_RENAME) charFlags |= CHARACTER_FLAG_RENAME; - if (fields[20].GetUInt32()) + if (fields[23].GetUInt32()) charFlags |= CHARACTER_FLAG_LOCKED_BY_BILLING; if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED)) { - if (!fields[21].GetString().empty()) + if (!fields[24].GetString().empty()) charFlags |= CHARACTER_FLAG_DECLINED; } else @@ -1700,17 +1711,17 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) // Pets info uint32 petDisplayId = 0; uint32 petLevel = 0; - uint32 petFamily = 0; + CreatureFamily petFamily = CREATURE_FAMILY_NONE; // show pet at selection character in character list only for non-ghost character if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (plrClass == CLASS_WARLOCK || plrClass == CLASS_HUNTER || plrClass == CLASS_DEATH_KNIGHT)) { - uint32 entry = fields[16].GetUInt32(); + uint32 entry = fields[19].GetUInt32(); CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(entry); if (creatureInfo) { - petDisplayId = fields[17].GetUInt32(); - petLevel = fields[18].GetUInt16(); + petDisplayId = fields[20].GetUInt32(); + petLevel = fields[21].GetUInt16(); petFamily = creatureInfo->family; } } @@ -1719,7 +1730,7 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) *data << uint32(petLevel); *data << uint32(petFamily); - Tokenizer equipment(fields[19].GetString(), ' '); + Tokenizer equipment(fields[22].GetString(), ' '); for (uint8 slot = 0; slot < INVENTORY_SLOT_BAG_END; ++slot) { uint32 visualBase = slot * 2; @@ -1739,7 +1750,7 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot) { // values stored in 2 uint16 - uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16); + uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot * 16); if (!enchantId) continue; @@ -1799,14 +1810,14 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati { if (!MapManager::IsValidMapCoord(mapid, x, y, z, orientation)) { - TC_LOG_ERROR("maps", "TeleportTo: invalid map (%d) or invalid coordinates (X: %f, Y: %f, Z: %f, O: %f) given when teleporting player (GUID: %u, name: %s, map: %d, X: %f, Y: %f, Z: %f, O: %f).", - mapid, x, y, z, orientation, GetGUID().GetCounter(), GetName().c_str(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); + TC_LOG_ERROR("maps", "Player::TeleportTo: Invalid map (%d) or invalid coordinates (X: %f, Y: %f, Z: %f, O: %f) given when teleporting player '%s' (%s, MapID: %d, X: %f, Y: %f, Z: %f, O: %f).", + mapid, x, y, z, orientation, GetGUID().ToString().c_str(), GetName().c_str(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); return false; } if (!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_DISABLE_MAP) && DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, mapid, this)) { - TC_LOG_ERROR("maps", "Player (GUID: %u, name: %s) tried to enter a forbidden map %u", GetGUID().GetCounter(), GetName().c_str(), mapid); + TC_LOG_ERROR("maps", "Player::TeleportTo: Player '%s' (%s) tried to enter a forbidden map (MapID: %u)", GetGUID().ToString().c_str(), GetName().c_str(), mapid); SendTransferAborted(mapid, TRANSFER_ABORT_MAP_NOT_ALLOWED); return false; } @@ -1824,7 +1835,8 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // client without expansion support if (GetSession()->Expansion() < mEntry->Expansion()) { - TC_LOG_DEBUG("maps", "Player %s using client without required expansion tried teleport to non accessible map %u", GetName().c_str(), mapid); + TC_LOG_DEBUG("maps", "Player '%s' (%s) using client without required expansion tried teleport to non accessible map (MapID: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), mapid); if (Transport* transport = GetTransport()) { @@ -1837,7 +1849,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati return false; // normal client can't teleport to this map... } else - TC_LOG_DEBUG("maps", "Player %s is being teleported to map %u", GetName().c_str(), mapid); + TC_LOG_DEBUG("maps", "Player %s (%s) is being teleported to map (MapID: %u)", GetName().c_str(), GetGUID().ToString().c_str(), mapid); if (m_vehicle) ExitVehicle(); @@ -1862,7 +1874,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if (GetMapId() == mapid) { - //lets reset far teleport flag if it wasn't reset during chained teleports + //lets reset far teleport flag if it wasn't reset during chained teleport SetSemaphoreTeleportFar(false); //setup delayed teleport flag SetDelayedTeleportFlag(IsCanDelayTeleport()); @@ -2046,24 +2058,7 @@ void Player::ProcessDelayedOperations() return; if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER) - { - ResurrectPlayer(0.0f, false); - - if (GetMaxHealth() > m_resurrectHealth) - SetHealth(m_resurrectHealth); - else - SetFullHealth(); - - if (GetMaxPower(POWER_MANA) > m_resurrectMana) - SetPower(POWER_MANA, m_resurrectMana); - else - SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); - - SetPower(POWER_RAGE, 0); - SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); - - SpawnCorpseBones(); - } + ResurrectUsingRequestDataImpl(); if (m_DelayedOperations & DELAYED_SAVE_PLAYER) SaveToDB(); @@ -2146,8 +2141,8 @@ void Player::RemoveFromWorld() { if (WorldObject* viewpoint = GetViewpoint()) { - TC_LOG_ERROR("entities.player", "Player %s has viewpoint %u %u when removed from world", - GetName().c_str(), viewpoint->GetEntry(), viewpoint->GetTypeId()); + TC_LOG_ERROR("entities.player", "Player::RemoveFromWorld: Player '%s' (%s) has viewpoint (Entry:%u, Type: %u) when removed from world", + GetName().c_str(), GetGUID().ToString().c_str(), viewpoint->GetEntry(), viewpoint->GetTypeId()); SetViewpoint(viewpoint, false); } } @@ -2388,14 +2383,14 @@ void Player::ResetAllPowers() } } -bool Player::CanInteractWithQuestGiver(Object* questGiver) +bool Player::CanInteractWithQuestGiver(Object* questGiver) const { switch (questGiver->GetTypeId()) { case TYPEID_UNIT: - return GetNPCIfCanInteractWith(questGiver->GetGUID(), UNIT_NPC_FLAG_QUESTGIVER) != NULL; + return GetNPCIfCanInteractWith(questGiver->GetGUID(), UNIT_NPC_FLAG_QUESTGIVER) != nullptr; case TYPEID_GAMEOBJECT: - return GetGameObjectIfCanInteractWith(questGiver->GetGUID(), GAMEOBJECT_TYPE_QUESTGIVER) != NULL; + return GetGameObjectIfCanInteractWith(questGiver->GetGUID(), GAMEOBJECT_TYPE_QUESTGIVER) != nullptr; case TYPEID_PLAYER: return IsAlive() && questGiver->ToPlayer()->IsAlive(); case TYPEID_ITEM: @@ -2406,46 +2401,46 @@ bool Player::CanInteractWithQuestGiver(Object* questGiver) return false; } -Creature* Player::GetNPCIfCanInteractWith(ObjectGuid const& guid, uint32 npcflagmask) +Creature* Player::GetNPCIfCanInteractWith(ObjectGuid const& guid, uint32 npcflagmask) const { // unit checks if (!guid) - return NULL; + return nullptr; if (!IsInWorld()) - return NULL; + return nullptr; if (IsInFlight()) - return NULL; + return nullptr; // exist (we need look pets also for some interaction (quest/etc) Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid); if (!creature) - return NULL; + return nullptr; // Deathstate checks - if (!IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_GHOST)) - return NULL; + if (!IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_GHOST_VISIBLE)) + return nullptr; // alive or spirit healer - if (!creature->IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_DEAD_INTERACT)) - return NULL; + if (!creature->IsAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_INTERACT_WHILE_DEAD)) + return nullptr; // appropriate npc type if (npcflagmask && !creature->HasFlag(UNIT_NPC_FLAGS, npcflagmask)) - return NULL; + return nullptr; // not allow interaction under control, but allow with own pets if (creature->GetCharmerGUID()) - return NULL; + return nullptr; // not unfriendly/hostile if (creature->GetReactionTo(this) <= REP_UNFRIENDLY) - return NULL; + return nullptr; // not too far if (!creature->IsWithinDistInMap(this, INTERACTION_DISTANCE)) - return NULL; + return nullptr; return creature; } @@ -2473,8 +2468,8 @@ GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid const& guid, Gameo if (go->IsWithinDistInMap(this, go->GetInteractionDistance())) return go; - TC_LOG_DEBUG("maps", "GetGameObjectIfCanInteractWith: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal %f is allowed)", go->GetGOInfo()->name.c_str(), - go->GetGUID().GetCounter(), GetName().c_str(), GetGUID().GetCounter(), go->GetDistance(this), go->GetInteractionDistance()); + TC_LOG_DEBUG("maps", "Player::GetGameObjectIfCanInteractWith: GameObject '%s' (%s) is too far away from player '%s' (%s) to be used by him (Distance: %f, maximal 10 is allowed)", + go->GetGOInfo()->name.c_str(), go->GetGUID().ToString().c_str(), GetName().c_str(), GetGUID().ToString().c_str(), go->GetDistance(this)); } } @@ -2625,14 +2620,14 @@ bool Player::IsGroupVisibleFor(Player const* p) const bool Player::IsInSameGroupWith(Player const* p) const { - return p == this || (GetGroup() != NULL && + return p == this || (GetGroup() != nullptr && GetGroup() == p->GetGroup() && GetGroup()->SameSubGroup(this, p)); } bool Player::IsInSameRaidWith(Player const* p) const { - return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); + return p == this || (GetGroup() != nullptr && GetGroup() == p->GetGroup()); } ///- If the player is invited, remove him. If the group if then only 1 person, disband the group. @@ -2667,7 +2662,7 @@ void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method group->RemoveMember(guid, method, kicker, reason); } -void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend, float /*group_rate*/) +void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend, float /*group_rate*/) const { WorldPacket data(SMSG_LOG_XPGAIN, 21); // guess size? data << uint64(victim ? victim->GetGUID() : ObjectGuid::Empty); @@ -2708,7 +2703,7 @@ void Player::GiveXP(uint32 xp, Unit* victim, float group_rate) if (level >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) return; - uint32 bonus_xp = 0; + uint32 bonus_xp; bool recruitAFriend = GetsRecruitAFriendBonus(true); // RaF does NOT stack with rested experience @@ -2799,6 +2794,8 @@ void Player::GiveLevel(uint8 level) if (sWorld->getBoolConfig(CONFIG_ALWAYS_MAXSKILL)) // Max weapon skill when leveling up UpdateSkillsToMaxSkillsForLevel(); + _ApplyAllLevelScaleItemMods(true); + // set current level health and mana/energy to maximum after applying all mods. SetFullHealth(); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); @@ -2808,8 +2805,6 @@ void Player::GiveLevel(uint8 level) SetPower(POWER_FOCUS, 0); SetPower(POWER_HAPPINESS, 0); - _ApplyAllLevelScaleItemMods(true); - // update level to hunter/summon pet if (Pet* pet = GetPet()) pet->SynchronizeLevelWithOwner(); @@ -2831,8 +2826,8 @@ void Player::GiveLevel(uint8 level) { ++m_grantableLevels; - if (!HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01)) - SetByteFlag(PLAYER_FIELD_BYTES, 1, 0x01); + if (!HasByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01)) + SetByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01); } sScriptMgr->OnPlayerLevelChanged(this, oldLevel); @@ -3002,7 +2997,7 @@ void Player::InitStatsForLevel(bool reapplyMods) // cleanup unit flags (will be re-applied if need at aura load). RemoveFlag(UNIT_FIELD_FLAGS, - UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 | + UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_LOOTING | UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED | @@ -3069,8 +3064,6 @@ void Player::SendInitialSpells() GetSpellHistory()->WritePacket<Player>(data); GetSession()->SendPacket(&data); - - TC_LOG_DEBUG("network", "CHARACTER: Sent Initial Spells"); } void Player::RemoveMail(uint32 id) @@ -3086,7 +3079,7 @@ void Player::RemoveMail(uint32 id) } } -void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, ObjectGuid::LowType item_guid, uint32 item_count) +void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, ObjectGuid::LowType item_guid, uint32 item_count) const { WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0)))); data << (uint32) mailId; @@ -3102,7 +3095,7 @@ void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResp GetSession()->SendPacket(&data); } -void Player::SendNewMail() +void Player::SendNewMail() const { // deliver undelivered mail WorldPacket data(SMSG_RECEIVED_MAIL, 4); @@ -3114,7 +3107,7 @@ void Player::UpdateNextMailTimeAndUnreads() { // calculate next delivery time (min. from non-delivered mails // and recalculate unReadMail - time_t cTime = time(NULL); + time_t cTime = time(nullptr); m_nextMailDelivereTime = 0; unReadMails = 0; for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) @@ -3131,7 +3124,7 @@ void Player::UpdateNextMailTimeAndUnreads() void Player::AddNewMailDeliverTime(time_t deliver_time) { - if (deliver_time <= time(NULL)) // ready now + if (deliver_time <= time(nullptr)) // ready now { ++unReadMails; SendNewMail(); @@ -3164,12 +3157,12 @@ bool Player::AddTalent(uint32 spellId, uint8 spec, bool learning) // do character spell book cleanup (all characters) if (!IsInWorld() && !learning) // spell load case { - TC_LOG_ERROR("spells", "Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.", spellId); + TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: %u) does not exist. Deleting for all characters in `character_spell` and `character_talent`.", spellId); DeleteSpellFromAllPlayers(spellId); } else - TC_LOG_ERROR("spells", "Player::addSpell: Non-existed in SpellStore spell #%u request.", spellId); + TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: %u) does not exist", spellId); return false; } @@ -3179,12 +3172,12 @@ bool Player::AddTalent(uint32 spellId, uint8 spec, bool learning) // do character spell book cleanup (all characters) if (!IsInWorld() && !learning) // spell load case { - TC_LOG_ERROR("spells", "Player::addTalent: Broken spell #%u learning not allowed, deleting for all characters in `character_talent`.", spellId); + TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: %u) is invalid. Deleting for all characters in `character_spell` and `character_talent`.", spellId); DeleteSpellFromAllPlayers(spellId); } else - TC_LOG_ERROR("spells", "Player::addTalent: Broken spell #%u learning not allowed.", spellId); + TC_LOG_ERROR("spells", "Player::AddTalent: Spell (ID: %u) is invalid", spellId); return false; } @@ -3209,10 +3202,9 @@ bool Player::AddTalent(uint32 spellId, uint8 spec, bool learning) } } - PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; PlayerTalent* newtalent = new PlayerTalent(); - newtalent->state = state; + newtalent->state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED; newtalent->spec = spec; (*m_talents[spec])[spellId] = newtalent; @@ -3229,12 +3221,12 @@ bool Player::AddSpell(uint32 spellId, bool active, bool learning, bool dependent // do character spell book cleanup (all characters) if (!IsInWorld() && !learning) // spell load case { - TC_LOG_ERROR("spells", "Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.", spellId); + TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: %u) does not exist. deleting for all characters in `character_spell` and `character_talent`.", spellId); DeleteSpellFromAllPlayers(spellId); } else - TC_LOG_ERROR("spells", "Player::addSpell: Non-existed in SpellStore spell #%u request.", spellId); + TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: %u) does not exist", spellId); return false; } @@ -3244,12 +3236,12 @@ bool Player::AddSpell(uint32 spellId, bool active, bool learning, bool dependent // do character spell book cleanup (all characters) if (!IsInWorld() && !learning) // spell load case { - TC_LOG_ERROR("spells", "Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.", spellId); + TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: %u) is invalid. deleting for all characters in `character_spell` and `character_talent`.", spellId); DeleteSpellFromAllPlayers(spellId); } else - TC_LOG_ERROR("spells", "Player::addSpell: Broken spell #%u learning not allowed.", spellId); + TC_LOG_ERROR("spells", "Player::AddSpell: Spell (ID: %u) is invalid", spellId); return false; } @@ -3852,7 +3844,7 @@ bool Player::Has310Flyer(bool checkAllSpells, uint32 excludeSpellId) if (_spell_idx->second->skillId != SKILL_MOUNTS) break; // We can break because mount spells belong only to one skillline (at least 310 flyers do) - spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + spellInfo = sSpellMgr->AssertSpellInfo(itr->first); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED && spellInfo->Effects[i].CalcValue() == 310) @@ -3872,7 +3864,7 @@ void Player::RemoveArenaSpellCooldowns(bool removeActivePetCooldowns) // remove cooldowns on spells that have < 10 min CD GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); return spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS; }, true); @@ -3939,12 +3931,12 @@ bool Player::ResetTalents(bool no_cost) if (!HasEnoughMoney(cost)) { - SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0); + SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, nullptr, 0, 0); return false; } } - RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { @@ -3966,7 +3958,7 @@ bool Player::ResetTalents(bool no_cost) for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) { - // skip non-existant talent ranks + // skip non-existing talent ranks if (talentInfo->RankID[rank] == 0) continue; const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]); @@ -4024,7 +4016,7 @@ Mail* Player::GetMail(uint32 id) if ((*itr)->messageID == id) return (*itr); - return NULL; + return nullptr; } void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const @@ -4033,7 +4025,7 @@ void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) c { for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->BuildCreateUpdateBlockForPlayer(data, target); @@ -4041,7 +4033,7 @@ void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) c for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->BuildCreateUpdateBlockForPlayer(data, target); @@ -4064,7 +4056,7 @@ void Player::DestroyForPlayer(Player* target, bool onDeath) const for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->DestroyForPlayer(target); @@ -4074,7 +4066,7 @@ void Player::DestroyForPlayer(Player* target, bool onDeath) const { for (uint8 i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->DestroyForPlayer(target); @@ -4164,7 +4156,7 @@ TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell } // check primary prof. limit - // first rank of primary profession spell when there are no proffesions avalible is disabled + // first rank of primary profession spell when there are no professions available is disabled for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!trainer_spell->learnedSpell[i]) @@ -4219,7 +4211,7 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe // close player ticket if any GmTicket* ticket = sTicketMgr->GetTicketByPlayer(playerguid); if (ticket) - ticket->SetClosedBy(playerguid); + sTicketMgr->CloseTicket(ticket->GetId(), playerguid); // remove from arena teams LeaveAllArenaTeams(playerguid); @@ -4542,7 +4534,8 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe break; } default: - TC_LOG_ERROR("entities.player", "Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method); + TC_LOG_ERROR("entities.player", "Player::DeleteFromDB: Tried to delete player (%s) with unsupported delete method (%u).", + playerguid.ToString().c_str(), charDelete_method); return; } @@ -4571,19 +4564,19 @@ void Player::DeleteOldCharacters() * * @see Player::DeleteFromDB * - * @param keepDays overrite the config option by another amount of days + * @param keepDays overwrite the config option by another amount of days */ void Player::DeleteOldCharacters(uint32 keepDays) { - TC_LOG_INFO("entities.player", "Player::DeleteOldChars: Removing characters older than %u day(s)", keepDays); + TC_LOG_INFO("entities.player", "Player::DeleteOldCharacters: Deleting all characters which have been deleted %u days before...", keepDays); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS); - stmt->setUInt32(0, uint32(time(NULL) - time_t(keepDays * DAY))); + stmt->setUInt32(0, uint32(time(nullptr) - time_t(keepDays * DAY))); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (result) { - TC_LOG_DEBUG("entities.player", "Player::DeleteOldChars: " UI64FMTD " character(s) to remove", result->GetRowCount()); + TC_LOG_DEBUG("entities.player", "Player::DeleteOldCharacters: Found " UI64FMTD " character(s) to delete", result->GetRowCount()); do { Field* fields = result->Fetch(); @@ -4632,7 +4625,7 @@ void Player::BuildPlayerRepop() WorldLocation corpseLocation = GetCorpseLocation(); if (corpseLocation.GetMapId() == GetMapId()) { - TC_LOG_ERROR("entities.player", "BuildPlayerRepop: player %s(%d) already has a corpse", GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::BuildPlayerRepop: Player '%s' (%s) already has a corpse", GetName().c_str(), GetGUID().ToString().c_str()); return; } @@ -4640,7 +4633,7 @@ void Player::BuildPlayerRepop() Corpse* corpse = CreateCorpse(); if (!corpse) { - TC_LOG_ERROR("entities.player", "Error creating corpse for Player %s [%u]", GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::BuildPlayerRepop: Error creating corpse for player '%s' (%s)", GetName().c_str(), GetGUID().ToString().c_str()); return; } GetMap()->AddToMap(corpse); @@ -4749,30 +4742,9 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) } } -void Player::SendGhoulResurrectRequest(Player* target) -{ - target->m_ghoulResurrectPlayerGUID = GetGUID(); - - WorldPacket data(SMSG_RESURRECT_REQUEST, 8 + 4 + 1 + 1); - data << uint64(GetGUID()); - data << uint32(0); - data << uint8(0); - data << uint8(0); - target->GetSession()->SendPacket(&data); -} - -void Player::GhoulResurrect() -{ - CastSpell(this, 46619 /*SPELL_DK_RAISE_ALLY*/, true, nullptr, nullptr, m_ghoulResurrectPlayerGUID); - - m_ghoulResurrectPlayerGUID = ObjectGuid::Empty; -} - void Player::RemoveGhoul() { - if (IsGhouled()) - if (Creature* ghoul = ObjectAccessor::GetCreature(*this, m_ghoulResurrectGhoulGUID)) - ghoul->DespawnOrUnsummon(); // Raise Ally aura will handle unauras + RemoveAura(SPELL_DK_RAISE_ALLY); } void Player::KillPlayer() @@ -4817,10 +4789,10 @@ void Player::OfflineResurrect(ObjectGuid const& guid, SQLTransaction& trans) Corpse* Player::CreateCorpse() { - // prevent existence 2 corpse for player + // prevent the existence of 2 corpses for one player SpawnCorpseBones(); - uint32 _pb, _pb2, _cfb1, _cfb2; + uint32 _cfb1, _cfb2; Corpse* corpse = new Corpse((m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE); SetPvPDeath(false); @@ -4833,16 +4805,13 @@ Corpse* Player::CreateCorpse() _corpseLocation.WorldRelocate(*this); - _pb = GetUInt32Value(PLAYER_BYTES); - _pb2 = GetUInt32Value(PLAYER_BYTES_2); - - uint8 skin = (uint8)(_pb); - uint8 face = (uint8)(_pb >> 8); - uint8 hairstyle = (uint8)(_pb >> 16); - uint8 haircolor = (uint8)(_pb >> 24); - uint8 facialhair = (uint8)(_pb2); + uint8 skin = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID); + uint8 face = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID); + uint8 hairstyle = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID); + uint8 haircolor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID); + uint8 facialhair = GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE); - _cfb1 = ((0x00) | (getRace() << 8) | (GetByteValue(PLAYER_BYTES_3, 0) << 16) | (skin << 24)); + _cfb1 = ((0x00) | (getRace() << 8) | (GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER) << 16) | (skin << 24)); _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24)); corpse->SetUInt32Value(CORPSE_FIELD_BYTES_1, _cfb1); @@ -4962,7 +4931,7 @@ void Player::DurabilityPointsLossAll(int32 points, bool inventory) //for (int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++) for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++) - if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + if (Bag* pBag = static_cast<Bag*>(GetItemByPos(INVENTORY_SLOT_BAG_0, i))) for (uint32 j = 0; j < pBag->GetBagSize(); j++) if (Item* pItem = GetItemByPos(i, j)) DurabilityPointsLoss(pItem, points); @@ -4971,6 +4940,9 @@ void Player::DurabilityPointsLossAll(int32 points, bool inventory) void Player::DurabilityPointsLoss(Item* item, int32 points) { + if (HasAuraType(SPELL_AURA_PREVENT_DURABILITY_LOSS)) + return; + int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY); int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY); int32 pNewDurability = pOldDurability - points; @@ -5042,7 +5014,8 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g DurabilityCostsEntry const* dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel); if (!dcost) { - TC_LOG_ERROR("entities.player.items", "RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel); + TC_LOG_ERROR("entities.player.items", "Player::DurabilityRepair: Player '%s' (%s) tried to repair an item (ItemID: %u) with invalid item level %u", + GetName().c_str(), GetGUID().ToString().c_str(), ditemProto->ItemId, ditemProto->ItemLevel); return TotalCost; } @@ -5050,7 +5023,8 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g DurabilityQualityEntry const* dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId); if (!dQualitymodEntry) { - TC_LOG_ERROR("entities.player.items", "RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId); + TC_LOG_ERROR("entities.player.items", "Player::DurabilityRepair: Player '%s' (%s) tried to repair an item (ItemID: %u) with invalid QualitymodEntry %u", + GetName().c_str(), GetGUID().ToString().c_str(), ditemProto->ItemId, dQualitymodEntryId); return TotalCost; } @@ -5066,7 +5040,8 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g { if (GetGuildId() == 0) { - TC_LOG_DEBUG("entities.player.items", "You are not member of a guild"); + TC_LOG_DEBUG("entities.player.items", "Player::DurabilityRepair: Player '%s' (%s) tried to repair item in a guild bank but is not member of a guild", + GetName().c_str(), GetGUID().ToString().c_str()); return TotalCost; } @@ -5081,7 +5056,8 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g } else if (!HasEnoughMoney(costs)) { - TC_LOG_DEBUG("entities.player.items", "You do not have enough money"); + TC_LOG_DEBUG("entities.player.items", "Player::DurabilityRepair: Player '%s' (%s) has not enough money to repair item", + GetName().c_str(), GetGUID().ToString().c_str()); return TotalCost; } else @@ -5112,7 +5088,7 @@ void Player::RepopAtGraveyard() SpawnCorpseBones(); } - WorldSafeLocsEntry const* ClosestGrave = NULL; + WorldSafeLocsEntry const* ClosestGrave; // Special handle for battleground maps if (Battleground* bg = GetBattleground()) @@ -5149,7 +5125,7 @@ void Player::RepopAtGraveyard() RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_IS_OUT_OF_BOUNDS); } -bool Player::CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone) +bool Player::CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone) const { if (channel->flags & CHANNEL_DBC_FLAG_ZONE_DEP && zone->flags & AREA_FLAG_ARENA_INSTANCE) return false; @@ -5183,7 +5159,7 @@ void Player::CleanupChannels() if (ChannelMgr* cMgr = ChannelMgr::forTeam(GetTeam())) cMgr->LeftChannel(ch->GetName()); // deleted channel if empty } - TC_LOG_DEBUG("chat.system", "Player %s: channels cleaned up!", GetName().c_str()); + TC_LOG_DEBUG("chat.system", "Player::CleanupChannels: Channels of player '%s' (%s) cleaned up.", GetName().c_str(), GetGUID().ToString().c_str()); } void Player::UpdateLocalChannels(uint32 newZone) @@ -5200,71 +5176,67 @@ void Player::UpdateLocalChannels(uint32 newZone) return; std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()]; - for (uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i) { - if (ChatChannelsEntry const* channel = sChatChannelsStore.LookupEntry(i)) - { - Channel* usedChannel = NULL; + ChatChannelsEntry const* channelEntry = sChatChannelsStore.LookupEntry(i); + if (!channelEntry) + continue; - for (JoinedChannelsList::iterator itr = m_channels.begin(); itr != m_channels.end(); ++itr) + Channel* usedChannel = nullptr; + for (Channel* channel : m_channels) + { + if (channel->GetChannelId() == i) { - if ((*itr)->GetChannelId() == i) - { - usedChannel = *itr; - break; - } + usedChannel = channel; + break; } + } - Channel* removeChannel = NULL; - Channel* joinChannel = NULL; - bool sendRemove = true; + Channel* removeChannel = nullptr; + Channel* joinChannel = nullptr; + bool sendRemove = true; - if (CanJoinConstantChannelInZone(channel, current_zone)) + if (CanJoinConstantChannelInZone(channelEntry, current_zone)) + { + if (!(channelEntry->flags & CHANNEL_DBC_FLAG_GLOBAL)) { - if (!(channel->flags & CHANNEL_DBC_FLAG_GLOBAL)) - { - if (channel->flags & CHANNEL_DBC_FLAG_CITY_ONLY && usedChannel) - continue; // Already on the channel, as city channel names are not changing - - char new_channel_name_buf[100]; - char const* currentNameExt; + if (channelEntry->flags & CHANNEL_DBC_FLAG_CITY_ONLY && usedChannel) + continue; // Already on the channel, as city channel names are not changing - if (channel->flags & CHANNEL_DBC_FLAG_CITY_ONLY) - currentNameExt = sObjectMgr->GetTrinityStringForDBCLocale(LANG_CHANNEL_CITY); - else - currentNameExt = current_zone_name.c_str(); - - snprintf(new_channel_name_buf, 100, channel->pattern[m_session->GetSessionDbcLocale()], currentNameExt); + std::string currentNameExt; + if (channelEntry->flags & CHANNEL_DBC_FLAG_CITY_ONLY) + currentNameExt = sObjectMgr->GetTrinityStringForDBCLocale(LANG_CHANNEL_CITY); + else + currentNameExt = current_zone_name; - joinChannel = cMgr->GetJoinChannel(new_channel_name_buf, channel->ChannelID); - if (usedChannel) + std::string newChannelName = Trinity::StringFormat(channelEntry->pattern[m_session->GetSessionDbcLocale()], currentNameExt.c_str()); + joinChannel = cMgr->GetJoinChannel(newChannelName, channelEntry->ChannelID); + if (usedChannel) + { + if (joinChannel != usedChannel) { - if (joinChannel != usedChannel) - { - removeChannel = usedChannel; - sendRemove = false; // Do not send leave channel, it already replaced at client - } - else - joinChannel = NULL; + removeChannel = usedChannel; + sendRemove = false; // Do not send leave channel, it already replaced at client } + else + joinChannel = nullptr; } - else - joinChannel = cMgr->GetJoinChannel(channel->pattern[m_session->GetSessionDbcLocale()], channel->ChannelID); } else - removeChannel = usedChannel; + joinChannel = cMgr->GetJoinChannel(channelEntry->pattern[m_session->GetSessionDbcLocale()], channelEntry->ChannelID); + } + else + removeChannel = usedChannel; - if (joinChannel) - joinChannel->JoinChannel(this, ""); // Changed Channel: ... or Joined Channel: ... + if (joinChannel) + joinChannel->JoinChannel(this, ""); // Changed Channel: ... or Joined Channel: ... - if (removeChannel) - { - removeChannel->LeaveChannel(this, sendRemove); // Leave old channel - std::string name = removeChannel->GetName(); // Store name, (*i)erase in LeftChannel - LeftChannel(removeChannel); // Remove from player's channel list - cMgr->LeftChannel(name); // Delete if empty - } + if (removeChannel) + { + removeChannel->LeaveChannel(this, sendRemove); // Leave old channel + std::string name = removeChannel->GetName(); // Store name, (*i)erase in LeftChannel + LeftChannel(removeChannel); // Remove from player's channel list + cMgr->LeftChannel(name); // Delete if empty } } } @@ -5291,7 +5263,8 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa { if (modGroup >= BASEMOD_END || modType >= MOD_END) { - TC_LOG_ERROR("spells", "ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!"); + TC_LOG_ERROR("spells", "Player::HandleBaseModValue: Invalid BaseModGroup/BaseModType (%u/%u) for player '%s' (%s)", + modGroup, modType, GetName().c_str(), GetGUID().ToString().c_str()); return; } @@ -5317,7 +5290,8 @@ float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const { if (modGroup >= BASEMOD_END || modType >= MOD_END) { - TC_LOG_ERROR("spells", "trial to access non existed BaseModGroup or wrong BaseModType!"); + TC_LOG_ERROR("spells", "Player::GetBaseModValue: Invalid BaseModGroup/BaseModType (%u/%u) for player '%s' (%s)", + modGroup, modType, GetName().c_str(), GetGUID().ToString().c_str()); return 0.0f; } @@ -5331,7 +5305,8 @@ float Player::GetTotalBaseModValue(BaseModGroup modGroup) const { if (modGroup >= BASEMOD_END) { - TC_LOG_ERROR("spells", "wrong BaseModGroup in GetTotalBaseModValue()!"); + TC_LOG_ERROR("spells", "Player::GetTotalBaseModValue: Invalid BaseModGroup (%u) for player '%s' (%s)", + modGroup, GetName().c_str(), GetGUID().ToString().c_str()); return 0.0f; } @@ -5350,7 +5325,7 @@ uint32 Player::GetShieldBlockValue() const return uint32(value); } -float Player::GetMeleeCritFromAgility() +float Player::GetMeleeCritFromAgility() const { uint8 level = getLevel(); uint32 pclass = getClass(); @@ -5360,14 +5335,14 @@ float Player::GetMeleeCritFromAgility() GtChanceToMeleeCritBaseEntry const* critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1); GtChanceToMeleeCritEntry const* critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - if (critBase == NULL || critRatio == NULL) + if (critBase == nullptr || critRatio == nullptr) return 0.0f; float crit = critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio; return crit*100.0f; } -void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) +void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) const { // Table for base dodge values const float dodge_base[MAX_CLASSES] = @@ -5408,7 +5383,7 @@ void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) // Dodge per agility is proportional to crit per agility, which is available from DBC files GtChanceToMeleeCritEntry const* dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - if (dodgeRatio == NULL || pclass > MAX_CLASSES) + if (dodgeRatio == nullptr || pclass > MAX_CLASSES) return; /// @todo research if talents/effects that increase total agility by x% should increase non-diminishing part @@ -5420,7 +5395,7 @@ void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing) nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]); } -float Player::GetSpellCritFromIntellect() +float Player::GetSpellCritFromIntellect() const { uint8 level = getLevel(); uint32 pclass = getClass(); @@ -5430,7 +5405,7 @@ float Player::GetSpellCritFromIntellect() GtChanceToSpellCritBaseEntry const* critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1); GtChanceToSpellCritEntry const* critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - if (critBase == NULL || critRatio == NULL) + if (critBase == nullptr || critRatio == nullptr) return 0.0f; float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio; @@ -5472,7 +5447,7 @@ float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const return 0.0f; } -float Player::OCTRegenHPPerSpirit() +float Player::OCTRegenHPPerSpirit() const { uint8 level = getLevel(); uint32 pclass = getClass(); @@ -5495,7 +5470,7 @@ float Player::OCTRegenHPPerSpirit() return regen; } -float Player::OCTRegenMPPerSpirit() +float Player::OCTRegenMPPerSpirit() const { uint8 level = getLevel(); uint32 pclass = getClass(); @@ -5505,7 +5480,7 @@ float Player::OCTRegenMPPerSpirit() // GtOCTRegenMPEntry const* baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenMPPerSptEntry const* moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - if (moreRatio == NULL) + if (moreRatio == nullptr) return 0.0f; // Formula get from PaperDollFrame script @@ -5703,7 +5678,8 @@ inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLeve bool Player::UpdateCraftSkill(uint32 spellid) { - TC_LOG_DEBUG("entities.player.skills", "UpdateCraftSkill spellid %d", spellid); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateCraftSkill: Player '%s' (%s), SpellID: %d", + GetName().c_str(), GetGUID().ToString().c_str(), spellid); SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellid); @@ -5735,7 +5711,8 @@ bool Player::UpdateCraftSkill(uint32 spellid) bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator) { - TC_LOG_DEBUG("entities.player.skills", "UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateGatherSkill: Player '%s' (%s), SkillID: %u, SkillLevel: %u, RedLevel: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), SkillId, SkillValue, RedLevel); uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING); @@ -5763,7 +5740,7 @@ bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLeve bool Player::UpdateFishingSkill() { - TC_LOG_DEBUG("entities.player.skills", "UpdateFishingSkill"); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateFishingSkill: Player '%s' (%s)", GetName().c_str(), GetGUID().ToString().c_str()); uint32 SkillValue = GetPureSkillValue(SKILL_FISHING); @@ -5782,13 +5759,15 @@ static const size_t bonusSkillLevelsSize = sizeof(bonusSkillLevels) / sizeof(uin bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) { - TC_LOG_DEBUG("entities.player.skills", "UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance / 10.0f); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '%s' (%s), SkillID: %u, Chance: %3.1f%%)", + GetName().c_str(), GetGUID().ToString().c_str(), SkillId, Chance / 10.0f); if (!SkillId) return false; if (Chance <= 0) // speedup in 0 chance case { - TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro Chance=%3.1f%% missed", Chance / 10.0f); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '%s' (%s), SkillID: %u, Chance: %3.1f%% missed", + GetName().c_str(), GetGUID().ToString().c_str(), SkillId, Chance / 10.0f); return false; } @@ -5827,11 +5806,13 @@ bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) } UpdateSkillEnchantments(SkillId, SkillValue, new_value); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, SkillId); - TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro Chance=%3.1f%% taken", Chance / 10.0f); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '%s' (%s), SkillID: %u, Chance: %3.1f%% taken", + GetName().c_str(), GetGUID().ToString().c_str(), SkillId, Chance / 10.0f); return true; } - TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro Chance=%3.1f%% missed", Chance / 10.0f); + TC_LOG_DEBUG("entities.player.skills", "Player::UpdateSkillPro: Player '%s' (%s), SkillID: %u, Chance: %3.1f%% missed", + GetName().c_str(), GetGUID().ToString().c_str(), SkillId, Chance / 10.0f); return false; } @@ -6065,7 +6046,8 @@ void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal) SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(id); if (!pSkill) { - TC_LOG_ERROR("entities.player.skills", "Skill not found in SkillLineStore: skill #%u", id); + TC_LOG_ERROR("misc", "Player::SetSkill: Skill (SkillID: %u) not found in SkillLineStore for player '%s' (%s)", + id, GetName().c_str(), GetGUID().ToString().c_str()); return; } @@ -6247,20 +6229,22 @@ void Player::SendActionButtons(uint32 state) const } GetSession()->SendPacket(&data); - TC_LOG_DEBUG("network", "SMSG_ACTION_BUTTONS sent '%u' spec '%u' Sent", GetGUID().GetCounter(), m_activeSpec); + } -bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) +bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) const { if (button >= MAX_ACTION_BUTTONS) { - TC_LOG_DEBUG("entities.player", "Action %u not added into button %u for player %s (GUID: %u): button must be < %u", action, button, GetName().c_str(), GetGUID().GetCounter(), MAX_ACTION_BUTTONS ); + TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Action %u not added into button %u for player %s (%s): button must be < %u", + action, button, GetName().c_str(), GetGUID().ToString().c_str(), MAX_ACTION_BUTTONS); return false; } if (action >= MAX_ACTION_BUTTON_ACTION_VALUE) { - TC_LOG_DEBUG("entities.player", "Action %u not added into button %u for player %s (GUID: %u): action must be < %u", action, button, GetName().c_str(), GetGUID().GetCounter(), MAX_ACTION_BUTTON_ACTION_VALUE); + TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Action %u not added into button %u for player %s (%s): action must be < %u", + action, button, GetName().c_str(), GetGUID().ToString().c_str(), MAX_ACTION_BUTTON_ACTION_VALUE); return false; } @@ -6269,20 +6253,23 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) case ACTION_BUTTON_SPELL: if (!sSpellMgr->GetSpellInfo(action)) { - TC_LOG_DEBUG("entities.player", "Spell action %u not added into button %u for player %s (GUID: %u): spell not exist", action, button, GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player", "Player::IsActionButtonDataValid: Spell action %u not added into button %u for player %s (%s): spell does not exist. This can be due to a character imported from a different expansion", + action, button, GetName().c_str(), GetGUID().ToString().c_str()); return false; } if (!HasSpell(action)) { - TC_LOG_DEBUG("entities.player", "Spell action %u not added into button %u for player %s (GUID: %u): player don't known this spell", action, button, GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player", "Player::IsActionButtonDataValid: Spell action %u not added into button %u for player %s (%s): player does not known this spell, this can be due to a player changing their talents", + action, button, GetName().c_str(), GetGUID().ToString().c_str()); return false; } break; case ACTION_BUTTON_ITEM: if (!sObjectMgr->GetItemTemplate(action)) { - TC_LOG_DEBUG("entities.player", "Item action %u not added into button %u for player %s (GUID: %u): item not exist", action, button, GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Item action %u not added into button %u for player %s (%s): item not exist", + action, button, GetName().c_str(), GetGUID().ToString().c_str()); return false; } break; @@ -6292,7 +6279,7 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) case ACTION_BUTTON_EQSET: break; default: - TC_LOG_DEBUG("entities.player", "Unknown action type %u", type); + TC_LOG_ERROR("entities.player", "Player::IsActionButtonDataValid: Unknown action type %u", type); return false; // other cases not checked at this moment } @@ -6302,15 +6289,16 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type) { if (!IsActionButtonDataValid(button, action, type)) - return NULL; + return nullptr; - // it create new button (NEW state) if need or return existed + // it create new button (NEW state) if need or return existing ActionButton& ab = m_actionButtons[button]; // set data and update to CHANGED if not NEW ab.SetActionAndType(action, ActionButtonType(type)); - TC_LOG_DEBUG("entities.player", "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUID().GetCounter(), action, type, button); + TC_LOG_DEBUG("entities.player", "Player::AddActionButton: Player '%s' (%s) added action '%u' (type %u) to button '%u'", + GetName().c_str(), GetGUID().ToString().c_str(), action, type, button); return &ab; } @@ -6325,14 +6313,15 @@ void Player::removeActionButton(uint8 button) else buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save - TC_LOG_DEBUG("entities.player", "Action Button '%u' Removed from Player '%u'", button, GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player", "Player::RemoveActionButton: Player '%s' (%s) removed action button '%u'", + GetName().c_str(), GetGUID().ToString().c_str(), button); } ActionButton const* Player::GetActionButton(uint8 button) { ActionButtonList::iterator buttonItr = m_actionButtons.find(button); if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED) - return NULL; + return nullptr; return &buttonItr->second; } @@ -6366,15 +6355,6 @@ bool Player::UpdatePosition(float x, float y, float z, float orientation, bool t return true; } -void Player::SaveRecallPosition() -{ - m_recallMap = GetMapId(); - m_recallX = GetPositionX(); - m_recallY = GetPositionY(); - m_recallZ = GetPositionZ(); - m_recallO = GetOrientation(); -} - void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self) { if (self) @@ -6404,19 +6384,21 @@ void Player::SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) VisitNearbyWorldObject(GetVisibilityRange(), notifier); } -void Player::SendDirectMessage(WorldPacket* data) +void Player::SendDirectMessage(WorldPacket const* data) const { m_session->SendPacket(data); } -void Player::SendCinematicStart(uint32 CinematicSequenceId) +void Player::SendCinematicStart(uint32 CinematicSequenceId) const { WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4); data << uint32(CinematicSequenceId); SendDirectMessage(&data); + if (CinematicSequencesEntry const* sequence = sCinematicSequencesStore.LookupEntry(CinematicSequenceId)) + _cinematicMgr->SetActiveCinematicCamera(sequence->cinematicCamera); } -void Player::SendMovieStart(uint32 MovieId) +void Player::SendMovieStart(uint32 MovieId) const { WorldPacket data(SMSG_TRIGGER_MOVIE, 4); data << uint32(MovieId); @@ -6475,7 +6457,7 @@ void Player::CheckAreaExploreAndOutdoor() else { int32 diff = int32(getLevel()) - areaEntry->area_level; - uint32 XP = 0; + uint32 XP; if (diff < -5) { XP = uint32(sObjectMgr->GetBaseXP(getLevel()+5)*sWorld->getRate(RATE_XP_EXPLORE)); @@ -6493,7 +6475,7 @@ void Player::CheckAreaExploreAndOutdoor() XP = uint32(sObjectMgr->GetBaseXP(areaEntry->area_level)*sWorld->getRate(RATE_XP_EXPLORE)); } - GiveXP(XP, NULL); + GiveXP(XP, nullptr); SendExplorationExperience(areaId, XP); } TC_LOG_DEBUG("entities.player", "Player '%s' (%s) discovered a new area: %u", GetName().c_str(),GetGUID().ToString().c_str(), areaId); @@ -6710,8 +6692,8 @@ void Player::RewardReputation(Quest const* quest) void Player::UpdateHonorFields() { /// called when rewarding honor and at each save - time_t now = time_t(time(NULL)); - time_t today = time_t(time(NULL) / DAY) * DAY; + time_t now = time_t(time(nullptr)); + time_t today = time_t(time(nullptr) / DAY) * DAY; if (m_lastHonorUpdateTime < today) { @@ -6835,7 +6817,7 @@ bool Player::RewardHonor(Unit* victim, uint32 groupsize, int32 honor, bool pvpto } } - if (victim != NULL) + if (victim != nullptr) { if (groupsize > 1) honor_f /= groupsize; @@ -6980,6 +6962,7 @@ void Player::SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type) SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId); SetArenaTeamInfoField(slot, ARENA_TEAM_TYPE, type); } + void Player::SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value) { SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value); @@ -7212,7 +7195,7 @@ void Player::CheckDuelDistance(time_t currTime) } } -bool Player::IsOutdoorPvPActive() +bool Player::IsOutdoorPvPActive() const { return IsAlive() && !HasInvisibilityAura() && !HasStealthAura() && IsPvP() && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !IsInFlight(); } @@ -7223,7 +7206,15 @@ void Player::DuelComplete(DuelCompleteType type) if (!duel) return; - TC_LOG_DEBUG("entities.unit", "Duel Complete %s %s", GetName().c_str(), duel->opponent->GetName().c_str()); + // Check if DuelComplete() has been called already up in the stack and in that case don't do anything else here + if (duel->isCompleted || ASSERT_NOTNULL(duel->opponent->duel)->isCompleted) + return; + + duel->isCompleted = true; + duel->opponent->duel->isCompleted = true; + + TC_LOG_DEBUG("entities.unit", "Player::DuelComplete: Player '%s' (%s), Opponent: '%s' (%s)", + GetName().c_str(), GetGUID().ToString().c_str(), duel->opponent->GetName().c_str(), duel->opponent->GetGUID().ToString().c_str()); WorldPacket data(SMSG_DUEL_COMPLETE, (1)); data << (uint8)((type != DUEL_INTERRUPTED) ? 1 : 0); @@ -7271,7 +7262,7 @@ void Player::DuelComplete(DuelCompleteType type) // Honor points after duel (the winner) - ImpConfig if (uint32 amount = sWorld->getIntConfig(CONFIG_HONOR_AFTER_DUEL)) - duel->opponent->RewardHonor(NULL, 1, amount); + duel->opponent->RewardHonor(nullptr, 1, amount); break; default: @@ -7326,9 +7317,9 @@ void Player::DuelComplete(DuelCompleteType type) duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0); delete duel->opponent->duel; - duel->opponent->duel = NULL; + duel->opponent->duel = nullptr; delete duel; - duel = NULL; + duel = nullptr; } //---------------------------------------------------------// @@ -7347,7 +7338,7 @@ void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply) if (item->IsBroken()) return; - TC_LOG_DEBUG("entities.player.items", "applying mods for item %u ", item->GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.items", "Player::_ApplyItemMods: Applying mods for item %s", item->GetGUID().ToString().c_str()); uint8 attacktype = Player::GetAttackBySlot(slot); @@ -7365,7 +7356,7 @@ void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply) ApplyItemEquipSpell(item, apply); ApplyEnchantment(item, apply); - TC_LOG_DEBUG("entities.player.items", "_ApplyItemMods complete."); + TC_LOG_DEBUG("entities.player.items", "Player::_ApplyItemMods: completed"); } void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale /*= false*/) @@ -7741,7 +7732,7 @@ void Player::_ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attac if (aura->GetSpellInfo()->EquippedItemClass == -1) return; - BaseModGroup mod = BASEMOD_END; + BaseModGroup mod; switch (attackType) { case BASE_ATTACK: mod = CRIT_PERCENTAGE; break; @@ -7768,7 +7759,7 @@ void Player::_ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType att if (aura->GetSpellInfo()->EquippedItemClass == -1) return; - UnitMods unitMod = UNIT_MOD_END; + UnitMods unitMod; switch (attackType) { case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; @@ -7777,7 +7768,7 @@ void Player::_ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType att default: return; } - UnitModifierType unitModType = TOTAL_VALUE; + UnitModifierType unitModType; switch (aura->GetAuraType()) { case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break; @@ -7844,7 +7835,8 @@ void Player::ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, return; } - TC_LOG_DEBUG("entities.player", "WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id); + TC_LOG_DEBUG("entities.player", "Player::ApplyEquipSpell: Player '%s' (%s) cast %s equip spell (ID: %i)", + GetName().c_str(), GetGUID().ToString().c_str(), (item ? "item" : "itemset"), spellInfo->Id); CastSpell(this, spellInfo, true, item); } @@ -7950,7 +7942,8 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId); if (!spellInfo) { - TC_LOG_ERROR("entities.player.items", "WORLD: unknown Item spellid %i", spellData.SpellId); + TC_LOG_ERROR("entities.player.items", "Player::CastItemCombatSpell: Player '%s' (%s) cast unknown item spell (ID: %i)", + GetName().c_str(), GetGUID().ToString().c_str(), spellData.SpellId); continue; } @@ -8005,8 +7998,8 @@ void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->spellid[s]); if (!spellInfo) { - TC_LOG_ERROR("entities.player.items", "Player::CastItemCombatSpell(GUID: %u, name: %s, enchant: %i): unknown spell %i is cast, ignoring...", - GetGUID().GetCounter(), GetName().c_str(), pEnchant->ID, pEnchant->spellid[s]); + TC_LOG_ERROR("entities.player.items", "Player::CastItemCombatSpell: Player '%s' (%s) cast unknown spell (EnchantID: %u, SpellID: %i), ignoring", + GetName().c_str(), GetGUID().ToString().c_str(), pEnchant->ID, pEnchant->spellid[s]); continue; } @@ -8050,7 +8043,7 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(learn_spell_id); if (!spellInfo) { - TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ", proto->ItemId, learn_spell_id); + TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) has wrong spell id %u, ignoring.", proto->ItemId, learn_spell_id); SendEquipError(EQUIP_ERR_NONE, item, NULL); return; } @@ -8079,7 +8072,7 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId); if (!spellInfo) { - TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring", proto->ItemId, spellData.SpellId); + TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) has wrong spell id %u, ignoring", proto->ItemId, spellData.SpellId); continue; } @@ -8106,7 +8099,7 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->spellid[s]); if (!spellInfo) { - TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]); + TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]); continue; } @@ -8325,7 +8318,7 @@ void Player::RemovedInsignia(Player* looterPlr) looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA); } -void Player::SendLootRelease(ObjectGuid guid) +void Player::SendLootRelease(ObjectGuid guid) const { WorldPacket data(SMSG_LOOT_RELEASE_RESPONSE, (8+1)); data << uint64(guid) << uint8(1); @@ -8337,13 +8330,13 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) if (ObjectGuid lguid = GetLootGUID()) m_session->DoLootRelease(lguid); - Loot* loot = 0; + Loot* loot; PermissionTypes permission = ALL_PERMISSION; - TC_LOG_DEBUG("loot", "Player::SendLoot"); + TC_LOG_DEBUG("loot", "Player::SendLoot: Player: '%s' (%s), Loot: %s", + GetName().c_str(), GetGUID().ToString().c_str(), guid.ToString().c_str()); if (guid.IsGameObject()) { - TC_LOG_DEBUG("loot", "IS_GAMEOBJECT_GUID(guid)"); GameObject* go = GetMap()->GetGameObject(guid); // not check distance for GO in case owned GO (fishing bobber case, for example) @@ -8552,7 +8545,6 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) } else { - permission = NONE_PERMISSION; SendLootError(guid, LOOT_ERROR_ALREADY_PICKPOCKETED); return; } @@ -8667,7 +8659,7 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); } -void Player::SendLootError(ObjectGuid guid, LootError error) +void Player::SendLootError(ObjectGuid guid, LootError error) const { WorldPacket data(SMSG_LOOT_RESPONSE, 10); data << uint64(guid); @@ -8676,20 +8668,20 @@ void Player::SendLootError(ObjectGuid guid, LootError error) SendDirectMessage(&data); } -void Player::SendNotifyLootMoneyRemoved() +void Player::SendNotifyLootMoneyRemoved() const { WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0); GetSession()->SendPacket(&data); } -void Player::SendNotifyLootItemRemoved(uint8 lootSlot) +void Player::SendNotifyLootItemRemoved(uint8 lootSlot) const { WorldPacket data(SMSG_LOOT_REMOVED, 1); data << uint8(lootSlot); GetSession()->SendPacket(&data); } -void Player::SendUpdateWorldState(uint32 Field, uint32 Value) +void Player::SendUpdateWorldState(uint32 Field, uint32 Value) const { WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8); data << Field; @@ -9324,7 +9316,7 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) SendBattlefieldWorldStates(); } -void Player::SendBGWeekendWorldStates() +void Player::SendBGWeekendWorldStates() const { for (uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i) { @@ -9339,7 +9331,7 @@ void Player::SendBGWeekendWorldStates() } } -void Player::SendBattlefieldWorldStates() +void Player::SendBattlefieldWorldStates() const { /// Send misc stuff that needs to be sent on every login, like the battle timers. if (sWorld->getBoolConfig(CONFIG_WINTERGRASP_ENABLE)) @@ -9348,7 +9340,7 @@ void Player::SendBattlefieldWorldStates() { SendUpdateWorldState(BATTLEFIELD_WG_WORLD_STATE_ACTIVE, wg->IsWarTime() ? 0 : 1); uint32 timer = wg->IsWarTime() ? 0 : (wg->GetTimer() / 1000); // 0 - Time to next battle - SendUpdateWorldState(ClockWorldState[1], uint32(time(NULL) + timer)); + SendUpdateWorldState(ClockWorldState[1], uint32(time(nullptr) + timer)); } } } @@ -9362,18 +9354,18 @@ uint32 Player::GetXPRestBonus(uint32 xp) SetRestBonus(GetRestBonus() - rested_bonus); - TC_LOG_DEBUG("entities.player", "GetXPRestBonus: Player %s (%u) gain %u xp (+%u Rested Bonus). Rested points=%f", GetName().c_str(), GetGUID().GetCounter(), xp+rested_bonus, rested_bonus, GetRestBonus()); + TC_LOG_DEBUG("entities.player", "Player::GetXPRestBonus: Player '%s' (%s) gain %u xp (+%u Rested Bonus). Rested points=%f", GetGUID().ToString().c_str(), GetName().c_str(), xp + rested_bonus, rested_bonus, GetRestBonus()); return rested_bonus; } -void Player::SetBindPoint(ObjectGuid guid) +void Player::SetBindPoint(ObjectGuid guid) const { WorldPacket data(SMSG_BINDER_CONFIRM, 8); data << uint64(guid); GetSession()->SendPacket(&data); } -void Player::SendTalentWipeConfirm(ObjectGuid guid) +void Player::SendTalentWipeConfirm(ObjectGuid guid) const { WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4)); data << uint64(guid); @@ -9394,7 +9386,7 @@ void Player::ResetPetTalents() CharmInfo* charmInfo = pet->GetCharmInfo(); if (!charmInfo) { - TC_LOG_ERROR("entities.player", "Object (GUID: %u TypeId: %u) is considered pet-like but doesn't have a charminfo!", pet->GetGUID().GetCounter(), pet->GetTypeId()); + TC_LOG_ERROR("entities.player", "Object (GUID: %u TypeId: %u) is considered pet-like, but doesn't have charm info!", pet->GetGUID().GetCounter(), pet->GetTypeId()); return; } pet->resetTalents(); @@ -9430,24 +9422,24 @@ void Player::SetSheath(SheathState sheathed) switch (sheathed) { case SHEATH_STATE_UNARMED: // no prepared weapon - SetVirtualItemSlot(0, NULL); - SetVirtualItemSlot(1, NULL); - SetVirtualItemSlot(2, NULL); + SetVirtualItemSlot(0, nullptr); + SetVirtualItemSlot(1, nullptr); + SetVirtualItemSlot(2, nullptr); break; case SHEATH_STATE_MELEE: // prepared melee weapon SetVirtualItemSlot(0, GetWeaponForAttack(BASE_ATTACK, true)); SetVirtualItemSlot(1, GetWeaponForAttack(OFF_ATTACK, true)); - SetVirtualItemSlot(2, NULL); + SetVirtualItemSlot(2, nullptr); break; case SHEATH_STATE_RANGED: // prepared ranged weapon - SetVirtualItemSlot(0, NULL); - SetVirtualItemSlot(1, NULL); + SetVirtualItemSlot(0, nullptr); + SetVirtualItemSlot(1, nullptr); SetVirtualItemSlot(2, GetWeaponForAttack(RANGED_ATTACK, true)); break; default: - SetVirtualItemSlot(0, NULL); - SetVirtualItemSlot(1, NULL); - SetVirtualItemSlot(2, NULL); + SetVirtualItemSlot(0, nullptr); + SetVirtualItemSlot(1, nullptr); + SetVirtualItemSlot(2, nullptr); break; } Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players... @@ -9795,7 +9787,7 @@ Item* Player::GetItemByGuid(ObjectGuid guid) const if (pItem->GetGUID() == guid) return pItem; - return NULL; + return nullptr; } Item* Player::GetItemByPos(uint16 pos) const @@ -9809,9 +9801,9 @@ Item* Player::GetItemByPos(uint8 bag, uint8 slot) const { if (bag == INVENTORY_SLOT_BAG_0 && (slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END))) return m_items[slot]; - else if (Bag* pBag = GetBagByPos(bag)) + if (Bag* pBag = GetBagByPos(bag)) return pBag->GetItemByPos(slot); - return NULL; + return nullptr; } //Does additional check for disarmed weapons @@ -9828,7 +9820,7 @@ Bag* Player::GetBagByPos(uint8 bag) const || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END)) if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, bag)) return item->ToBag(); - return NULL; + return nullptr; } Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= false*/) const @@ -9839,41 +9831,41 @@ Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= f case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break; case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break; case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break; - default: return NULL; + default: return nullptr; } - Item* item = NULL; + Item* item; if (useable) item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot); else item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!item || item->GetTemplate()->Class != ITEM_CLASS_WEAPON) - return NULL; + return nullptr; if (!useable) return item; if (item->IsBroken() || IsInFeralForm()) - return NULL; + return nullptr; return item; } Item* Player::GetShield(bool useable) const { - Item* item = NULL; + Item* item; if (useable) item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); else item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if (!item || item->GetTemplate()->Class != ITEM_CLASS_ARMOR) - return NULL; + return nullptr; if (!useable) return item; if (item->IsBroken()) - return NULL; + return nullptr; return item; } @@ -9933,7 +9925,7 @@ bool Player::IsBagPos(uint16 pos) return false; } -bool Player::IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) +bool Player::IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) const { // post selected if (bag == NULL_BAG && !explicit_pos) @@ -10190,7 +10182,7 @@ InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= NULL*/) const { - return CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count); + return CanStoreItem(bag, slot, dest, item, count, nullptr, false, no_space_count); } InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap /*= false*/) const @@ -10198,7 +10190,7 @@ InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& des if (!pItem) return EQUIP_ERR_ITEM_NOT_FOUND; uint32 count = pItem->GetCount(); - return CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, NULL); + return CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, nullptr); } bool Player::HasItemTotemCategory(uint32 TotemCategory) const @@ -10237,7 +10229,7 @@ InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemP // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) - pItem2 = NULL; + pItem2 = nullptr; uint32 need_space; @@ -10311,7 +10303,7 @@ InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, Ite if (bag == skip_bag) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; - // skip not existed bag or self targeted bag + // skip non-existing bag or self targeted bag Bag* pBag = GetBagByPos(bag); if (!pBag || pBag == pSrcItem) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; @@ -10323,7 +10315,7 @@ InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, Ite if (!pBagProto) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; - // specialized bag mode or non-specilized + // specialized bag mode or non-specialized if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER)) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; @@ -10340,10 +10332,10 @@ InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, Ite // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) - pItem2 = NULL; + pItem2 = nullptr; // if merge skip empty, if !merge skip non-empty - if ((pItem2 != NULL) != merge) + if ((pItem2 != nullptr) != merge) continue; uint32 need_space = pProto->GetMaxStackSize(); @@ -10351,8 +10343,7 @@ InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, Ite if (pItem2) { // can be merged at least partly - uint8 res = pItem2->CanBeMergedPartlyWith(pProto); - if (res != EQUIP_ERR_OK) + if (pItem2->CanBeMergedPartlyWith(pProto) != EQUIP_ERR_OK) continue; // descrease at current stacksize @@ -10391,10 +10382,10 @@ InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 sl // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) - pItem2 = NULL; + pItem2 = nullptr; // if merge skip empty, if !merge skip non-empty - if ((pItem2 != NULL) != merge) + if ((pItem2 != nullptr) != merge) continue; uint32 need_space = pProto->GetMaxStackSize(); @@ -10402,8 +10393,7 @@ InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 sl if (pItem2) { // can be merged at least partly - uint8 res = pItem2->CanBeMergedPartlyWith(pProto); - if (res != EQUIP_ERR_OK) + if (pItem2->CanBeMergedPartlyWith(pProto) != EQUIP_ERR_OK) continue; // descrease at current stacksize @@ -10428,7 +10418,7 @@ InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 sl InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item* pItem, bool swap, uint32* no_space_count) const { - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count); + TC_LOG_DEBUG("entities.player.items", "Player::CanStoreItem: Bag: %u, Slot: %u, Item: %u, Count: %u", bag, slot, entry, count); ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry); if (!pProto) @@ -10913,7 +10903,8 @@ InventoryResult Player::CanStoreItems(Item** items, int count, uint32* itemLimit if (!item) continue; - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanStoreItems %i. item = %u, count = %u", k + 1, item->GetEntry(), item->GetCount()); + TC_LOG_DEBUG("entities.player.items", "Player::CanStoreItems: Player '%s' (%s), Index: %i ItemID: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), k + 1, item->GetEntry(), item->GetCount()); ItemTemplate const* pProto = item->GetTemplate(); // strange item @@ -11080,7 +11071,7 @@ InventoryResult Player::CanStoreItems(Item** items, int count, uint32* itemLimit continue; // search free slot in bags - for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) + for (uint8 t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t) { if (Bag* bag = GetBagByPos(t)) { @@ -11130,7 +11121,8 @@ InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool dest = 0; if (pItem) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount()); + TC_LOG_DEBUG("entities.player.items", "Player::CanEquipItem: Player '%s' (%s), Slot: %u, Item: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), slot, pItem->GetEntry(), pItem->GetCount()); ItemTemplate const* pProto = pItem->GetTemplate(); if (pProto) { @@ -11296,11 +11288,12 @@ InventoryResult Player::CanUnequipItem(uint16 pos, bool swap) const Item* pItem = GetItemByPos(pos); - // Applied only to existed equipped item + // Applied only to existing equipped item if (!pItem) return EQUIP_ERR_OK; - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount()); + TC_LOG_DEBUG("entities.player.items", "Player::CanUnequipItem: Player '%s' (%s), Slot: %u, Item: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), pos, pItem->GetEntry(), pItem->GetCount()); ItemTemplate const* pProto = pItem->GetTemplate(); if (!pProto) @@ -11336,7 +11329,8 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest uint32 count = pItem->GetCount(); - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount()); + TC_LOG_DEBUG("entities.player.items", "Player::CanBankItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), bag, slot, pItem->GetEntry(), pItem->GetCount()); ItemTemplate const* pProto = pItem->GetTemplate(); if (!pProto) return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; @@ -11352,8 +11346,8 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest uint8 pItemslot = pItem->GetSlot(); if (pItemslot >= CURRENCYTOKEN_SLOT_START && pItemslot < CURRENCYTOKEN_SLOT_END) { - TC_LOG_ERROR("entities.player", "Possible hacking attempt: Player %s [guid: %u] tried to move token [guid: %u, entry: %u] out of the currency bag!", - GetName().c_str(), GetGUID().GetCounter(), pItem->GetGUID().GetCounter(), pProto->ItemId); + TC_LOG_ERROR("entities.player", "Possible hacking attempt: Player %s (%s) tried to move token [%s entry: %u] out of the currency bag!", + GetName().c_str(), GetGUID().ToString().c_str(), pItem->GetGUID().ToString().c_str(), pProto->ItemId); return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED; } @@ -11520,7 +11514,8 @@ InventoryResult Player::CanUseItem(Item* pItem, bool not_loading) const { if (pItem) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: CanUseItem item = %u", pItem->GetEntry()); + TC_LOG_DEBUG("entities.player.items", "Player::CanUseItem: Player '%s' (%s), Item: %u", + GetName().c_str(), GetGUID().ToString().c_str(), pItem->GetEntry()); if (!IsAlive() && not_loading) return EQUIP_ERR_YOU_ARE_DEAD; @@ -11801,7 +11796,7 @@ Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update) { if (!pItem) - return NULL; + return nullptr; Item* lastItem = pItem; for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();) @@ -11826,12 +11821,13 @@ Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update) Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update) { if (!pItem) - return NULL; + return nullptr; uint8 bag = pos >> 8; uint8 slot = pos & 255; - TC_LOG_DEBUG("entities.player.items", "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.items", "Player::_StoreItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u (%s), Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), bag, slot, pItem->GetEntry(), pItem->GetGUID().ToString().c_str(), count); Item* pItem2 = GetItemByPos(bag, slot); @@ -11843,7 +11839,7 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool pItem->SetCount(count); if (!pItem) - return NULL; + return nullptr; if (pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM || @@ -11859,7 +11855,7 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool pItem->SetGuidValue(ITEM_FIELD_OWNER, GetGUID()); pItem->SetSlot(slot); - pItem->SetContainer(NULL); + pItem->SetContainer(nullptr); // need update known currency if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END) @@ -11944,7 +11940,7 @@ Item* Player::EquipNewItem(uint16 pos, uint32 item, bool update) return EquipItem(pos, pItem, update); } - return NULL; + return nullptr; } Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) @@ -11977,7 +11973,8 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cooldownSpell); if (!spellProto) - TC_LOG_ERROR("entities.player", "Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell); + TC_LOG_ERROR("entities.player", "Player::EquipItem: Weapon switch cooldown spell %u for player '%s' (%s) couldn't be found in Spell.dbc", + cooldownSpell, GetName().c_str(), GetGUID().ToString().c_str()); else { m_weaponChangeTimer = spellProto->StartRecoveryTime; @@ -12097,14 +12094,15 @@ void Player::VisualizeItem(uint8 slot, Item* pItem) if (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED || pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM) pItem->SetBinding(true); - TC_LOG_DEBUG("entities.player.items", "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry()); + TC_LOG_DEBUG("entities.player.items", "Player::SetVisibleItemSlot: Player '%s' (%s), Slot: %u, Item: %u", + GetName().c_str(), GetGUID().ToString().c_str(), slot, pItem->GetEntry()); m_items[slot] = pItem; SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID()); pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetGUID()); pItem->SetGuidValue(ITEM_FIELD_OWNER, GetGUID()); pItem->SetSlot(slot); - pItem->SetContainer(NULL); + pItem->SetContainer(nullptr); if (slot < EQUIPMENT_SLOT_END) SetVisibleItemSlot(slot, pItem); @@ -12127,7 +12125,8 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) Item* pItem = GetItemByPos(bag, slot); if (pItem) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); + TC_LOG_DEBUG("entities.player.items", "Player::RemoveItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u", + GetName().c_str(), GetGUID().ToString().c_str(), bag, slot, pItem->GetEntry()); RemoveEnchantmentDurations(pItem); RemoveItemDurations(pItem); @@ -12148,7 +12147,8 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) // remove item dependent auras and casts (only weapon and armor slots) if (slot < EQUIPMENT_SLOT_END) { - RemoveItemDependentAurasAndCasts(pItem); + if (update) + RemoveItemDependentAurasAndCasts(pItem); // remove held enchantments, update expertise if (slot == EQUIPMENT_SLOT_MAINHAND) @@ -12181,11 +12181,11 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) } } - m_items[slot] = NULL; + m_items[slot] = nullptr; SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty); if (slot < EQUIPMENT_SLOT_END) - SetVisibleItemSlot(slot, NULL); + SetVisibleItemSlot(slot, nullptr); } else if (Bag* pBag = GetBagByPos(bag)) pBag->RemoveItem(slot, update); @@ -12225,7 +12225,7 @@ void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool // store item Item* pLastItem = StoreItem(dest, pItem, update); - // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way) + // only set if not merged to existing stack (pItem can be deleted already but we can compare pointers any way) if (pLastItem == pItem) { // update owner for last item (this can be original item with wrong owner @@ -12246,7 +12246,8 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) Item* pItem = GetItemByPos(bag, slot); if (pItem) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry()); + TC_LOG_DEBUG("entities.player.items", "Player::DestroyItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u", + GetName().c_str(), GetGUID().ToString().c_str(), bag, slot, pItem->GetEntry()); // Also remove all contained items if the item is a bag. // This if () prevents item saving crashes if the condition for a bag to be empty before being destroyed was bypassed somehow. if (pItem->IsNotEmptyBag()) @@ -12315,10 +12316,10 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) UpdateExpertise(OFF_ATTACK); // equipment visual show - SetVisibleItemSlot(slot, NULL); + SetVisibleItemSlot(slot, nullptr); } - m_items[slot] = NULL; + m_items[slot] = nullptr; } else if (Bag* pBag = GetBagByPos(bag)) pBag->RemoveItem(slot, update); @@ -12326,7 +12327,7 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) // Delete rolled money / loot from db. // MUST be done before RemoveFromWorld() or GetTemplate() fails if (ItemTemplate const* pTmp = pItem->GetTemplate()) - if (pTmp->Flags & ITEM_PROTO_FLAG_OPENABLE) + if (pTmp->Flags & ITEM_PROTO_FLAG_HAS_LOOT) pItem->ItemContainerDeleteLootMoneyAndLootItemsFromDB(); if (IsInWorld() && update) @@ -12344,7 +12345,8 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) void Player::DestroyItemCount(uint32 itemEntry, uint32 count, bool update, bool unequip_check) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: DestroyItemCount item = %u, count = %u", itemEntry, count); + TC_LOG_DEBUG("entities.player.items", "Player::DestroyItemCount: Player '%s' (%s), Item: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), itemEntry, count); uint32 remcount = 0; // in inventory @@ -12535,7 +12537,8 @@ void Player::DestroyItemCount(uint32 itemEntry, uint32 count, bool update, bool void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone); + TC_LOG_DEBUG("entities.player.items", "Player::DestroyZoneLimitedItem: In map %u and area %u for player '%s' (%s)", + GetMapId(), new_zone, GetName().c_str(), GetGUID().ToString().c_str()); // in inventory for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) @@ -12567,7 +12570,8 @@ void Player::DestroyConjuredItems(bool update) { // used when entering arena // destroys all conjured items - TC_LOG_DEBUG("entities.player.items", "STORAGE: DestroyConjuredItems"); + TC_LOG_DEBUG("entities.player.items", "Player::DestroyConjuredItems: Player '%s' (%s)", + GetName().c_str(), GetGUID().ToString().c_str()); // in inventory for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++) @@ -12593,7 +12597,7 @@ void Player::DestroyConjuredItems(bool update) Item* Player::GetItemByEntry(uint32 entry) const { // in inventory - for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) + for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEntry() == entry) return pItem; @@ -12603,19 +12607,19 @@ Item* Player::GetItemByEntry(uint32 entry) const if (pItem->GetEntry() == entry) return pItem; - for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) + for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = GetBagByPos(i)) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->GetEntry() == entry) return pItem; - for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) + for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEntry() == entry) return pItem; - return NULL; + return nullptr; } void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update) @@ -12623,7 +12627,8 @@ void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update) if (!pItem) return; - TC_LOG_DEBUG("entities.player.items", "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUID().GetCounter(), pItem->GetEntry(), count); + TC_LOG_DEBUG("entities.player.items", "Player::DestroyItemCount: Player '%s' (%s), Item (%s, Entry: %u), Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), pItem->GetGUID().ToString().c_str(), pItem->GetEntry(), count); if (pItem->GetCount() <= count) { @@ -12653,28 +12658,28 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) Item* pSrcItem = GetItemByPos(srcbag, srcslot); if (!pSrcItem) { - SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL); + SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, nullptr); return; } if (pSrcItem->m_lootGenerated) // prevent split looting item (item { //best error message found for attempting to split while looting - SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL); + SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, nullptr); return; } // not let split all items (can be only at cheating) if (pSrcItem->GetCount() == count) { - SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL); + SendEquipError(EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, nullptr); return; } - // not let split more existed items (can be only at cheating) + // not let split more existing items (can be only at cheating) if (pSrcItem->GetCount() < count) { - SendEquipError(EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL); + SendEquipError(EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, nullptr); return; } @@ -12686,11 +12691,12 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) return; } - TC_LOG_DEBUG("entities.player.items", "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count); + TC_LOG_DEBUG("entities.player.items", "Player::SplitItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u, Count: %u", + GetName().c_str(), GetGUID().ToString().c_str(), dstbag, dstslot, pSrcItem->GetEntry(), count); Item* pNewItem = pSrcItem->CloneItem(count, this); if (!pNewItem) { - SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL); + SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, nullptr); return; } @@ -12705,7 +12711,7 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) { delete pNewItem; pSrcItem->SetCount(pSrcItem->GetCount() + count); - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12725,7 +12731,7 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) { delete pNewItem; pSrcItem->SetCount(pSrcItem->GetCount() + count); - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12745,7 +12751,7 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) { delete pNewItem; pSrcItem->SetCount(pSrcItem->GetCount() + count); - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12771,7 +12777,8 @@ void Player::SwapItem(uint16 src, uint16 dst) if (!pSrcItem) return; - TC_LOG_DEBUG("entities.player.items", "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry()); + TC_LOG_DEBUG("entities.player.items", "Player::SwapItem: Player '%s' (%s), Bag: %u, Slot: %u, Item: %u", + GetName().c_str(), GetGUID().ToString().c_str(), dstbag, dstslot, pSrcItem->GetEntry()); if (!IsAlive()) { @@ -12836,7 +12843,7 @@ void Player::SwapItem(uint16 src, uint16 dst) InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pSrcItem, false); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12851,7 +12858,7 @@ void Player::SwapItem(uint16 src, uint16 dst) InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pSrcItem, false); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12865,7 +12872,7 @@ void Player::SwapItem(uint16 src, uint16 dst) InventoryResult msg = CanEquipItem(dstslot, dest, pSrcItem, false); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, pSrcItem, NULL); + SendEquipError(msg, pSrcItem, nullptr); return; } @@ -12974,8 +12981,8 @@ void Player::SwapItem(uint16 src, uint16 dst) { if (Bag* dstBag = pDstItem->ToBag()) { - Bag* emptyBag = NULL; - Bag* fullBag = NULL; + Bag* emptyBag = nullptr; + Bag* fullBag = nullptr; if (srcBag->IsEmpty() && !IsBagPos(src)) { emptyBag = srcBag; @@ -13088,7 +13095,6 @@ void Player::SwapItem(uint16 src, uint16 dst) if (bagItem->m_lootGenerated) { m_session->DoLootRelease(GetLootGUID()); - released = true; // not realy needed here break; } } @@ -13133,10 +13139,11 @@ void Player::AddItemToBuyBackSlot(Item* pItem) } RemoveItemFromBuyBackSlot(slot, true); - TC_LOG_DEBUG("entities.player.items", "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot); + TC_LOG_DEBUG("entities.player.items", "Player::AddItemToBuyBackSlot: Player '%s' (%s), Item: %u, Slot: %u", + GetName().c_str(), GetGUID().ToString().c_str(), pItem->GetEntry(), slot); m_items[slot] = pItem; - time_t base = time(NULL); + time_t base = time(nullptr); uint32 etime = uint32(base - m_logintime + (30 * 3600)); uint32 eslot = slot - BUYBACK_SLOT_START; @@ -13155,15 +13162,17 @@ void Player::AddItemToBuyBackSlot(Item* pItem) Item* Player::GetItemFromBuyBackSlot(uint32 slot) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: GetItemFromBuyBackSlot slot = %u", slot); + TC_LOG_DEBUG("entities.player.items", "Player::GetItemFromBuyBackSlot: Player '%s' (%s), Slot: %u", + GetName().c_str(), GetGUID().ToString().c_str(), slot); if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) return m_items[slot]; - return NULL; + return nullptr; } void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del) { - TC_LOG_DEBUG("entities.player.items", "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot); + TC_LOG_DEBUG("entities.player.items", "Player::RemoveItemFromBuyBackSlot: Player '%s' (%s), Slot: %u", + GetName().c_str(), GetGUID().ToString().c_str(), slot); if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) { Item* pItem = m_items[slot]; @@ -13174,7 +13183,7 @@ void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del) pItem->SetState(ITEM_REMOVED, this); } - m_items[slot] = NULL; + m_items[slot] = nullptr; uint32 eslot = slot - BUYBACK_SLOT_START; SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid::Empty); @@ -13187,9 +13196,9 @@ void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del) } } -void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint32 itemid) +void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint32 itemid) const { - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg); + WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18)); data << uint8(msg); @@ -13230,9 +13239,8 @@ void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint GetSession()->SendPacket(&data); } -void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) +void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) const { - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_BUY_FAILED"); WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1)); data << uint64(creature ? creature->GetGUID() : ObjectGuid::Empty); data << uint32(item); @@ -13242,9 +13250,8 @@ void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 GetSession()->SendPacket(&data); } -void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param) +void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param) const { - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_SELL_ITEM"); WorldPacket data(SMSG_SELL_ITEM, (8+8+(param?4:0)+1)); // last check 2.0.10 data << uint64(creature ? creature->GetGUID() : ObjectGuid::Empty); data << uint64(guid); @@ -13280,9 +13287,9 @@ void Player::TradeCancel(bool sendback) // cleanup delete m_trade; - m_trade = NULL; + m_trade = nullptr; delete trader->m_trade; - trader->m_trade = NULL; + trader->m_trade = nullptr; } } @@ -13314,7 +13321,8 @@ void Player::UpdateItemDuration(uint32 time, bool realtimeonly) if (m_itemDuration.empty()) return; - TC_LOG_DEBUG("entities.player.items", "Player::UpdateItemDuration(%u, %u)", time, realtimeonly); + TC_LOG_DEBUG("entities.player.items", "Player::UpdateItemDuration: Player '%s' (%s), Time: %u, RealTimeOnly: %u", + GetName().c_str(), GetGUID().ToString().c_str(), time, realtimeonly); for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();) { @@ -13775,7 +13783,7 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool { if (getClass() == CLASS_SHAMAN) { - float addValue = 0.0f; + float addValue; if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) { addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f); @@ -13796,10 +13804,11 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool // nothing do.. break; default: - TC_LOG_ERROR("entities.player", "Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type); + TC_LOG_ERROR("entities.player", "Player::ApplyEnchantment: Unknown item enchantment (ID: %u, DisplayType: %u) for player '%s' (%s)", + enchant_id, enchant_display_type, GetName().c_str(), GetGUID().ToString().c_str()); break; - } /*switch (enchant_display_type)*/ - } /*for*/ + } + } } // visualize enchantment at player and equipped items @@ -13967,7 +13976,7 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool VendorItemData const* vendorItems = creature->GetVendorItems(); if (!vendorItems || vendorItems->Empty()) { - TC_LOG_ERROR("sql.sql", "Creature %s (Entry: %u GUID: %u DB GUID: %u) has UNIT_NPC_FLAG_VENDOR set but has an empty trading item list.", creature->GetName().c_str(), creature->GetEntry(), creature->GetGUID().GetCounter(), creature->GetSpawnId()); + TC_LOG_ERROR("sql.sql", "Creature %s (Entry: %u GUID: %u DB GUID: %u) has UNIT_NPC_FLAG_VENDOR set, but has an empty trading item list.", creature->GetName().c_str(), creature->GetEntry(), creature->GetGUID().GetCounter(), creature->GetSpawnId()); canTalk = false; } break; @@ -14001,8 +14010,11 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool break; case GOSSIP_OPTION_TRAINER: if (getClass() != creature->GetCreatureTemplate()->trainer_class && creature->GetCreatureTemplate()->trainer_type == TRAINER_TYPE_CLASS) - TC_LOG_ERROR("sql.sql", "GOSSIP_OPTION_TRAINER:: Player %s (GUID: %u) request wrong gossip menu: %u with wrong class: %u at Creature: %s (Entry: %u, Trainer Class: %u)", - GetName().c_str(), GetGUID().GetCounter(), menu->GetGossipMenu().GetMenuId(), getClass(), creature->GetName().c_str(), creature->GetEntry(), creature->GetCreatureTemplate()->trainer_class); + { + TC_LOG_ERROR("sql.sql", "GOSSIP_OPTION_TRAINER:: Player %s (GUID: %u) requested wrong gossip menu: %u with wrong class: %u at Creature: %s (Entry: %u, Trainer Class: %u)", + GetName().c_str(), GetGUID().GetCounter(), menu->GetGossipMenu().GetMenuId(), getClass(), creature->GetName().c_str(), creature->GetEntry(), creature->GetCreatureTemplate()->trainer_class); + canTalk = false; + } // no break; case GOSSIP_OPTION_GOSSIP: case GOSSIP_OPTION_SPIRITGUIDE: @@ -14017,7 +14029,7 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool canTalk = false; break; default: - TC_LOG_ERROR("sql.sql", "Creature entry %u has unknown gossip option %u for menu %u", creature->GetEntry(), itr->second.OptionType, itr->second.MenuId); + TC_LOG_ERROR("sql.sql", "Creature entry %u has unknown gossip option %u for menu %u.", creature->GetEntry(), itr->second.OptionType, itr->second.MenuId); canTalk = false; break; } @@ -14058,14 +14070,14 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool if (!optionBroadcastText) { /// Find localizations from database. - if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR32(menuId, menuId))) + if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR32(menuId, itr->second.OptionIndex))) ObjectMgr::GetLocaleString(gossipMenuLocale->OptionText, locale, strOptionText); } if (!boxBroadcastText) { /// Find localizations from database. - if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR32(menuId, menuId))) + if (GossipMenuItemsLocale const* gossipMenuLocale = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR32(menuId, itr->second.OptionIndex))) ObjectMgr::GetLocaleString(gossipMenuLocale->BoxText, locale, strBoxText); } } @@ -14130,7 +14142,8 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men { if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER) { - TC_LOG_ERROR("entities.player", "Player guid %u request invalid gossip option for GameObject entry %u", GetGUID().GetCounter(), source->GetEntry()); + TC_LOG_ERROR("entities.player", "Player '%s' (%s) requests invalid gossip option for GameObject (Entry: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), source->GetEntry()); return; } } @@ -14142,7 +14155,7 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men int32 cost = int32(item->BoxMoney); if (!HasEnoughMoney(cost)) { - SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0); + SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, nullptr, 0, 0); PlayerTalkClass->SendCloseGossip(); return; } @@ -14167,7 +14180,7 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men break; case GOSSIP_OPTION_SPIRITHEALER: if (isDead()) - source->ToCreature()->CastSpell(source->ToCreature(), 17251, true, NULL, NULL, GetGUID()); + source->ToCreature()->CastSpell(source->ToCreature(), 17251, true, nullptr, nullptr, GetGUID()); break; case GOSSIP_OPTION_QUESTGIVER: PrepareQuestMenu(guid); @@ -14188,8 +14201,8 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men { // Cast spells that teach dual spec // Both are also ImplicitTarget self and must be cast by player - CastSpell(this, 63680, true, NULL, NULL, GetGUID()); - CastSpell(this, 63624, true, NULL, NULL, GetGUID()); + CastSpell(this, 63680, true, nullptr, nullptr, GetGUID()); + CastSpell(this, 63624, true, nullptr, nullptr, GetGUID()); // Should show another Gossip text with "Congratulations..." PlayerTalkClass->SendCloseGossip(); @@ -14234,7 +14247,8 @@ void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 men if (bgTypeId == BATTLEGROUND_TYPE_NONE) { - TC_LOG_ERROR("entities.player", "a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player '%s' (%s) requested battlegroundlist from an invalid creature (%s)", + GetName().c_str(), GetGUID().ToString().c_str(), source->GetGUID().ToString().c_str()); return; } @@ -14442,7 +14456,7 @@ bool Player::IsActiveQuest(uint32 quest_id) const return m_QuestStatus.find(quest_id) != m_QuestStatus.end(); } -Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) +Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) const { QuestRelationBounds objectQR; @@ -14459,7 +14473,7 @@ Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) if (pGameObject) objectQR = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry()); else - return NULL; + return nullptr; } uint32 nextQuestID = quest->GetNextQuestInChain(); @@ -14469,7 +14483,7 @@ Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) return sObjectMgr->GetQuestTemplate(nextQuestID); } - return NULL; + return nullptr; } bool Player::CanSeeStartQuest(Quest const* quest) @@ -14499,7 +14513,7 @@ bool Player::CanTakeQuest(Quest const* quest, bool msg) && SatisfyQuestConditions(quest, msg); } -bool Player::CanAddQuest(Quest const* quest, bool msg) +bool Player::CanAddQuest(Quest const* quest, bool msg) const { if (!SatisfyQuestLog(msg)) return false; @@ -14514,9 +14528,9 @@ bool Player::CanAddQuest(Quest const* quest, bool msg) // player already have max number (in most case 1) source item, no additional item needed and quest can be added. if (msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS) return true; - else if (msg2 != EQUIP_ERR_OK) + if (msg2 != EQUIP_ERR_OK) { - SendEquipError(msg2, NULL, NULL, srcitem); + SendEquipError(msg2, nullptr, nullptr, srcitem); return false; } } @@ -14635,7 +14649,7 @@ bool Player::CanRewardQuest(Quest const* quest, bool msg) GetItemCount(quest->RequiredItemId[i]) < quest->RequiredItemCount[i]) { if (msg) - SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, quest->RequiredItemId[i]); + SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr, quest->RequiredItemId[i]); return false; } } @@ -14667,7 +14681,7 @@ void Player::AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver) case TYPEID_ITEM: case TYPEID_CONTAINER: { - Item* item = (Item*)questGiver; + Item* item = static_cast<Item*>(questGiver); sScriptMgr->OnQuestAccept(this, item, quest); // destroy not required for quest finish quest starting item @@ -14709,7 +14723,7 @@ bool Player::CanRewardQuest(Quest const* quest, uint32 reward, bool msg) InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardChoiceItemId[reward], quest->RewardChoiceItemCount[reward]); if (res != EQUIP_ERR_OK) { - SendEquipError(res, NULL, NULL, quest->RewardChoiceItemId[reward]); + SendEquipError(res, nullptr, nullptr, quest->RewardChoiceItemId[reward]); return false; } } @@ -14724,7 +14738,7 @@ bool Player::CanRewardQuest(Quest const* quest, uint32 reward, bool msg) InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardItemId[i], quest->RewardItemIdCount[i]); if (res != EQUIP_ERR_OK) { - SendEquipError(res, NULL, NULL, quest->RewardItemId[i]); + SendEquipError(res, nullptr, nullptr, quest->RewardItemId[i]); return false; } } @@ -14787,7 +14801,7 @@ void Player::AddQuest(Quest const* quest, Object* questGiver) AddTimedQuest(quest_id); questStatusData.Timer = timeAllowed * IN_MILLISECONDS; - qtime = static_cast<uint32>(time(NULL)) + timeAllowed; + qtime = static_cast<uint32>(time(nullptr)) + timeAllowed; } else questStatusData.Timer = 0; @@ -14804,7 +14818,7 @@ void Player::AddQuest(Quest const* quest, Object* questGiver) StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, quest_id); - SendQuestUpdate(quest_id); + SendQuestUpdate(); if (sWorld->getBoolConfig(CONFIG_QUEST_ENABLE_QUEST_TRACKER)) // check if Quest Tracker is enabled { @@ -14831,17 +14845,13 @@ void Player::CompleteQuest(uint32 quest_id) SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE); if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id)) - { if (qInfo->HasFlag(QUEST_FLAGS_TRACKING)) RewardQuest(qInfo, 0, this, false); - else - SendQuestComplete(quest_id); - } } if (sWorld->getBoolConfig(CONFIG_QUEST_ENABLE_QUEST_TRACKER)) // check if Quest Tracker is enabled { - // prepare Quest Tracker datas + // prepare Quest Tracker data PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_QUEST_TRACK_COMPLETE_TIME); stmt->setUInt32(0, quest_id); stmt->setUInt32(1, GetGUID().GetCounter()); @@ -14872,15 +14882,23 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, uint32 quest_id = quest->GetQuestId(); for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) - if (quest->RequiredItemId[i]) - DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true); - + { + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i])) + { + if (quest->RequiredItemCount[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->RequiredItemId[i], 9999, true, true); + else + DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true, true); + } + } for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) { - if (quest->ItemDrop[i]) + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i])) { - uint32 count = quest->ItemDropQuantity[i]; - DestroyItemCount(quest->ItemDrop[i], count ? count : 9999, true); + if (quest->ItemDropQuantity[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->ItemDrop[i], 9999, true, true); + else + DestroyItemCount(quest->ItemDrop[i], quest->ItemDropQuantity[i], true, true); } } @@ -14935,7 +14953,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, int32 moneyRew = 0; if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) - GiveXP(XP, NULL); + GiveXP(XP, nullptr); else moneyRew = int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY)); @@ -14953,7 +14971,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, // honor reward if (uint32 honor = quest->CalculateHonorGain(getLevel())) - RewardHonor(NULL, 0, honor); + RewardHonor(nullptr, 0, honor); // title reward if (quest->GetCharTitleId()) @@ -14976,7 +14994,10 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, { /// @todo Poor design of mail system SQLTransaction trans = CharacterDatabase.BeginTransaction(); - MailDraft(mail_template_id).SendMailTo(trans, this, questGiver, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs()); + if (uint32 questMailSender = quest->GetRewMailSenderEntry()) + MailDraft(mail_template_id).SendMailTo(trans, this, questMailSender, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs()); + else + MailDraft(mail_template_id).SendMailTo(trans, this, questGiver, MAIL_CHECK_MASK_HAS_BODY, quest->GetRewMailDelaySecs()); CharacterDatabase.CommitTransaction(trans); } @@ -14997,13 +15018,16 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, SetSeasonalQuestStatus(quest_id); RemoveActiveQuest(quest_id, false); - m_RewardedQuests.insert(quest_id); - m_RewardedQuestsSave[quest_id] = QUEST_DEFAULT_SAVE_TYPE; + if (quest->CanIncreaseRewardedQuestCounters()) + { + m_RewardedQuests.insert(quest_id); + m_RewardedQuestsSave[quest_id] = QUEST_DEFAULT_SAVE_TYPE; + } // StoreNewItem, mail reward, etc. save data directly to the database // to prevent exploitable data desynchronisation we save the quest status to the database too // (to prevent rewarding this quest another time while rewards were already given out) - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); _SaveQuestStatus(trans); if (announce) @@ -15044,7 +15068,9 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, UpdatePvPState(); } - SendQuestUpdate(quest_id); + SendQuestUpdate(); + + SendQuestGiverStatusMultiple(); //lets remove flag for delayed teleports SetCanDelayTeleport(false); @@ -15082,14 +15108,32 @@ void Player::FailQuest(uint32 questId) SendQuestFailed(questId); // Destroy quest items on quest failure. - for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) - if (quest->RequiredItemId[i] > 0 && quest->RequiredItemCount[i] > 0) - // Destroy items received on starting the quest. - DestroyItemCount(quest->RequiredItemId[i], quest->RequiredItemCount[i], true, true); + for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i])) + if (quest->RequiredItemCount[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->RequiredItemId[i], 9999, true, true); + for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) - if (quest->ItemDrop[i] > 0 && quest->ItemDropQuantity[i] > 0) - // Destroy items received during the quest. - DestroyItemCount(quest->ItemDrop[i], quest->ItemDropQuantity[i], true, true); + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i])) + if (quest->ItemDropQuantity[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->ItemDrop[i], 9999, true, true); + } +} + +void Player::AbandonQuest(uint32 questId) +{ + if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId)) + { + // Destroy quest items on quest abandon. + for (uint8 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i])) + if (quest->RequiredItemCount[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->RequiredItemId[i], 9999, true, true); + + for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) + if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->ItemDrop[i])) + if (quest->ItemDropQuantity[i] > 0 && (itemTemplate->Bonding == BIND_QUEST_ITEM || itemTemplate->Bonding == BIND_QUEST_ITEM1)) + DestroyItemCount(quest->ItemDrop[i], 9999, true, true); } } @@ -15107,7 +15151,8 @@ bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestSkill: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required skill value.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestSkill: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have the required skill value.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15116,30 +15161,33 @@ bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const return true; } -bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const { if (getLevel() < qInfo->GetMinLevel()) { if (msg) { SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_LOW_LEVEL); - TC_LOG_DEBUG("misc", "SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (questId: %u) because player does not have required (min) level.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (QuestID: %u) because player '%s' (%s) doesn't have the required (min) level.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } - else if (qInfo->GetMaxLevel() > 0 && getLevel() > qInfo->GetMaxLevel()) + + if (qInfo->GetMaxLevel() > 0 && getLevel() > qInfo->GetMaxLevel()) { if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); // There doesn't seem to be a specific response for too high player level - TC_LOG_DEBUG("misc", "SatisfyQuestLevel: Sent INVALIDREASON_QUEST_FAILED_LOW_LEVEL (questId: %u) because player does not have required (max) level.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestLevel: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have the required (max) level.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } return true; } -bool Player::SatisfyQuestLog(bool msg) +bool Player::SatisfyQuestLog(bool msg) const { // exist free slot if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE) @@ -15149,7 +15197,6 @@ bool Player::SatisfyQuestLog(bool msg) { WorldPacket data(SMSG_QUESTLOG_FULL, 0); GetSession()->SendPacket(&data); - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTLOG_FULL"); } return false; } @@ -15193,7 +15240,8 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (1).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have the required quest (1).", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15226,7 +15274,8 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (2).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have the required quest (2).", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15242,7 +15291,8 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required quest (3).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestPreviousQuest: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have required quest (3).", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15260,7 +15310,8 @@ bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestClass: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required class.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestClass: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't have required class.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15269,7 +15320,7 @@ bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const return true; } -bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const { uint32 reqraces = qInfo->GetAllowableRaces(); if (reqraces == 0) @@ -15279,7 +15330,8 @@ bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE); - TC_LOG_DEBUG("misc", "SatisfyQuestRace: Sent INVALIDREASON_QUEST_FAILED_WRONG_RACE (questId: %u) because player does not have required race.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestRace: Sent INVALIDREASON_QUEST_FAILED_WRONG_RACE (QuestID: %u) because player '%s' (%s) doesn't have required race.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15295,7 +15347,8 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (min).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't required reputation (min).", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15306,7 +15359,8 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (max).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't required reputation (max).", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15319,7 +15373,7 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have required reputation (ReputationObjective2).", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "SatisfyQuestReputation: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not have the required reputation (ReputationObjective2).", qInfo->GetQuestId()); } return false; } @@ -15327,14 +15381,15 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) return true; } -bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const { if (GetQuestStatus(qInfo->GetQuestId()) != QUEST_STATUS_NONE) { if (msg) { SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON); - TC_LOG_DEBUG("misc", "SatisfyQuestStatus: Sent INVALIDREASON_QUEST_ALREADY_ON (questId: %u) because player quest status is not NONE.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestStatus: Sent INVALIDREASON_QUEST_ALREADY_ON (QuestID: %u) because player '%s' (%s) quest status is not NONE.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15348,7 +15403,8 @@ bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestConditions: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player does not meet conditions.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestConditions: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) doesn't meet conditions.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } TC_LOG_DEBUG("condition", "Player::SatisfyQuestConditions: conditions not met for quest %u", qInfo->GetQuestId()); return false; @@ -15356,14 +15412,15 @@ bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg) return true; } -bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const { if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED)) { if (msg) { SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED); - TC_LOG_DEBUG("misc", "SatisfyQuestTimed: Sent INVALIDREASON_QUEST_ONLY_ONE_TIMED (questId: %u) because player is already on a timed quest.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestTimed: Sent INVALIDREASON_QUEST_ONLY_ONE_TIMED (QuestID: %u) because player '%s' (%s) is already on a timed quest.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15394,7 +15451,8 @@ bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did daily quests in exclusive group.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) already did daily quests in exclusive group.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; @@ -15406,7 +15464,8 @@ bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did quest in exclusive group.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestExclusiveGroup: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) already did quest in exclusive group.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15414,7 +15473,7 @@ bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) return true; } -bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) const { uint32 nextQuest = qInfo->GetNextQuestInChain(); if (!nextQuest) @@ -15426,7 +15485,8 @@ bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did or started next quest in chain.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) already did or started next quest in chain.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15453,7 +15513,8 @@ bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) if (msg) { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); - TC_LOG_DEBUG("misc", "SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (questId: %u) because player already did or started next quest in chain.", qInfo->GetQuestId()); + TC_LOG_DEBUG("misc", "Player::SatisfyQuestNextChain: Sent INVALIDREASON_DONT_HAVE_REQ (QuestID: %u) because player '%s' (%s) already did or started next quest in chain.", + qInfo->GetQuestId(), GetName().c_str(), GetGUID().ToString().c_str()); } return false; } @@ -15468,14 +15529,14 @@ bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) return true; } -bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) +bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const { if (!qInfo->IsDaily() && !qInfo->IsDFQuest()) return true; if (qInfo->IsDFQuest()) { - if (!m_DFQuests.empty()) + if (m_DFQuests.find(qInfo->GetQuestId()) != m_DFQuests.end()) return false; return true; @@ -15556,8 +15617,8 @@ bool Player::GiveQuestSourceItem(Quest const* quest) // player already have max amount required item, just report success else if (msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS) return true; - else - SendEquipError(msg, NULL, NULL, srcitem); + + SendEquipError(msg, nullptr, nullptr, srcitem); return false; } @@ -15586,7 +15647,7 @@ bool Player::TakeQuestSourceItem(uint32 questId, bool msg) if (res != EQUIP_ERR_OK) { if (msg) - SendEquipError(res, NULL, NULL, srcItemId); + SendEquipError(res, nullptr, nullptr, srcItemId); return false; } @@ -15662,14 +15723,16 @@ bool Player::CanShareQuest(uint32 quest_id) const void Player::SetQuestStatus(uint32 questId, QuestStatus status, bool update /*= true*/) { - if (sObjectMgr->GetQuestTemplate(questId)) + if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId)) { m_QuestStatus[questId].Status = status; - m_QuestStatusSave[questId] = QUEST_DEFAULT_SAVE_TYPE; + + if (!quest->IsAutoComplete()) + m_QuestStatusSave[questId] = QUEST_DEFAULT_SAVE_TYPE; } if (update) - SendQuestUpdate(questId); + SendQuestUpdate(); sScriptMgr->OnQuestStatusChange(this, questId, status); } @@ -15684,7 +15747,7 @@ void Player::RemoveActiveQuest(uint32 questId, bool update /*= true*/) } if (update) - SendQuestUpdate(questId); + SendQuestUpdate(); } void Player::RemoveRewardedQuest(uint32 questId, bool update /*= true*/) @@ -15697,33 +15760,26 @@ void Player::RemoveRewardedQuest(uint32 questId, bool update /*= true*/) } if (update) - SendQuestUpdate(questId); + SendQuestUpdate(); } -void Player::SendQuestUpdate(uint32 questId) +void Player::SendQuestUpdate() { uint32 zone = 0, area = 0; + GetZoneAndAreaId(zone, area); - SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(questId); - if (saBounds.first != saBounds.second) - { - GetZoneAndAreaId(zone, area); + SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(area); - for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) - if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area)) - if (!HasAura(itr->second->spellId)) - CastSpell(this, itr->second->spellId, true); - } - - saBounds = sSpellMgr->GetSpellAreaForQuestEndMapBounds(questId); if (saBounds.first != saBounds.second) { - if (!zone || !area) - GetZoneAndAreaId(zone, area); - for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) + { if (!itr->second->IsFitToRequirements(this, zone, area)) RemoveAurasDueToSpell(itr->second->spellId); + else if (itr->second->autocast) + if (!HasAura(itr->second->spellId)) + CastSpell(this, itr->second->spellId, true); + } } UpdateForQuestWorldObjects(); @@ -15832,15 +15888,17 @@ QuestGiverStatus Player::GetQuestDialogStatus(Object* questgiver) } // not used in Trinity, but used in scripting code -uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) +uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) const { Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id); if (!qInfo) return 0; - for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) - if (qInfo->RequiredNpcOrGo[j] == entry) - return m_QuestStatus[quest_id].CreatureOrGOCount[j]; + auto itr = m_QuestStatus.find(quest_id); + if (itr != m_QuestStatus.end()) + for (uint8 j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) + if (qInfo->RequiredNpcOrGo[j] == entry) + return itr->second.CreatureOrGOCount[j]; return 0; } @@ -15963,7 +16021,7 @@ void Player::GroupEventHappens(uint32 questId, WorldObject const* pEventObject) { if (Group* group = GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); @@ -16073,7 +16131,7 @@ void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid /*= ObjectGuid::E { uint16 addkillcount = 1; uint32 real_entry = entry; - Creature* killed = NULL; + Creature* killed = nullptr; if (guid) { killed = GetMap()->GetCreature(guid); @@ -16426,21 +16484,19 @@ bool Player::HasQuestForItem(uint32 itemid) const return false; } -void Player::SendQuestComplete(uint32 quest_id) +void Player::SendQuestComplete(uint32 quest_id) const { if (quest_id) { WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4); data << uint32(quest_id); GetSession()->SendPacket(&data); - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id); } } -void Player::SendQuestReward(Quest const* quest, uint32 XP) +void Player::SendQuestReward(Quest const* quest, uint32 XP) const { uint32 questid = quest->GetQuestId(); - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid); sGameEventMgr->HandleQuestComplete(questid); WorldPacket data(SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4)); data << uint32(questid); @@ -16462,7 +16518,7 @@ void Player::SendQuestReward(Quest const* quest, uint32 XP) GetSession()->SendPacket(&data); } -void Player::SendQuestFailed(uint32 questId, InventoryResult reason) +void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const { if (questId) { @@ -16470,11 +16526,10 @@ void Player::SendQuestFailed(uint32 questId, InventoryResult reason) data << uint32(questId); data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message) GetSession()->SendPacket(&data); - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED"); } } -void Player::SendQuestTimerFailed(uint32 quest_id) +void Player::SendQuestTimerFailed(uint32 quest_id) const { if (quest_id) { @@ -16493,7 +16548,7 @@ void Player::SendCanTakeQuestResponse(QuestFailedReason msg) const TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID"); } -void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver) +void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver) const { if (pReceiver) { @@ -16514,7 +16569,7 @@ void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver) } } -void Player::SendPushToPartyResponse(Player* player, uint8 msg) +void Player::SendPushToPartyResponse(Player* player, uint8 msg) const { if (player) { @@ -16526,7 +16581,7 @@ void Player::SendPushToPartyResponse(Player* player, uint8 msg) } } -void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, uint16 /*count*/) +void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, uint16 /*count*/) const { WorldPacket data(SMSG_QUESTUPDATE_ADD_ITEM, 0); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM"); @@ -16563,7 +16618,6 @@ void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint ASSERT(old_count + add_count < 65536 && "player count store in 16 bits"); WorldPacket data(SMSG_QUESTUPDATE_ADD_PVP_KILL, (3*4)); - TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_ADD_PVP_KILL"); data << uint32(quest->GetQuestId()); data << uint32(old_count + add_count); data << uint32(quest->GetPlayersSlain()); @@ -16574,6 +16628,50 @@ void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint SetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT, GetQuestSlotCounter(log_slot, QUEST_PVP_KILL_SLOT) + add_count); } +void Player::SendQuestGiverStatusMultiple() +{ + uint32 count = 0; + + WorldPacket data(SMSG_QUESTGIVER_STATUS_MULTIPLE, 4); + data << uint32(count); // placeholder + + for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr) + { + uint32 questStatus = DIALOG_STATUS_NONE; + + if (itr->IsAnyTypeCreature()) + { + // need also pet quests case support + Creature* questgiver = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr); + if (!questgiver || questgiver->IsHostileTo(this)) + continue; + if (!questgiver->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER)) + continue; + + questStatus = GetQuestDialogStatus(questgiver); + + data << uint64(questgiver->GetGUID()); + data << uint8(questStatus); + ++count; + } + else if (itr->IsGameObject()) + { + GameObject* questgiver = GetMap()->GetGameObject(*itr); + if (!questgiver || questgiver->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER) + continue; + + questStatus = GetQuestDialogStatus(questgiver); + + data << uint64(questgiver->GetGUID()); + data << uint8(questStatus); + ++count; + } + } + + data.put<uint32>(0, count); // write real count + GetSession()->SendPacket(&data); +} + bool Player::HasPvPForcingQuest() const { for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i) @@ -16771,22 +16869,22 @@ bool Player::IsLoading() const bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) { - //// 0 1 2 3 4 5 6 7 8 9 10 11 - //QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, " - // 12 13 14 15 16 17 18 19 20 21 22 23 24 + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + //QueryResult* result = CharacterDatabase.PQuery("SELECT guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " + // 17 18 19 20 21 22 23 24 25 26 27 28 29 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, " - // 25 26 27 28 29 30 31 32 33 34 35 36 37 38 + // 30 31 32 33 34 35 36 37 38 39 40 41 42 43 //"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, " - // 39 40 41 42 43 44 45 46 47 48 49 + // 44 45 46 47 48 49 50 51 52 53 54 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, " - // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 + // 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 //"health, power1, power2, power3, power4, power5, power6, power7, instance_id, talentGroupsCount, activeTalentGroup, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", guid); PreparedQueryResult result = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_FROM); if (!result) { std::string name = "<unknown>"; sObjectMgr->GetPlayerNameByGUID(guid, name); - TC_LOG_ERROR("entities.player", "Player %s %s not found in table `characters`, can't load. ", name.c_str(), guid.ToString().c_str()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player '%s' (%s) not found in table `characters`, can't load. ", name.c_str(), guid.ToString().c_str()); return false; } @@ -16798,13 +16896,13 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) // player should be able to load/delete character only with correct account! if (dbAccountId != GetSession()->GetAccountId()) { - TC_LOG_ERROR("entities.player", "Player %s loading from wrong account (is: %u, should be: %u)", guid.ToString().c_str(), GetSession()->GetAccountId(), dbAccountId); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) loading from wrong account (is: %u, should be: %u)", guid.ToString().c_str(), GetSession()->GetAccountId(), dbAccountId); return false; } if (holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BANNED)) { - TC_LOG_ERROR("entities.player", "%s is banned, can't load.", guid.ToString().c_str()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) is banned, can't load.", guid.ToString().c_str()); return false; } @@ -16814,8 +16912,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) // check name limitations if (ObjectMgr::CheckPlayerName(m_name, GetSession()->GetSessionDbcLocale()) != CHAR_NAME_SUCCESS || - (!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && - sObjectMgr->IsReservedName(m_name))) + (!GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHARACTER_CREATION_RESERVEDNAME) && sObjectMgr->IsReservedName(m_name))) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->setUInt16(0, uint16(AT_LOGIN_RENAME)); @@ -16830,30 +16927,27 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) uint8 gender = fields[5].GetUInt8(); if (!IsValidGender(gender)) { - TC_LOG_ERROR("entities.player", "Player %s has wrong gender (%u), can't be loaded.", guid.ToString().c_str(), gender); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has wrong gender (%u), can't load.", guid.ToString().c_str(), gender); return false; } - // overwrite some data fields - uint32 bytes0 = 0; - bytes0 |= fields[3].GetUInt8(); // race - bytes0 |= fields[4].GetUInt8() << 8; // class - bytes0 |= gender << 16; // gender - SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_RACE, fields[3].GetUInt8()); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, fields[4].GetUInt8()); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, gender); // check if race/class combination is valid PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass()); if (!info) { - TC_LOG_ERROR("entities.player", "Player %s has wrong race/class (%u/%u), can't be loaded.", guid.ToString().c_str(), getRace(), getClass()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has wrong race/class (%u/%u), can't load.", guid.ToString().c_str(), getRace(), getClass()); return false; } SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8()); SetUInt32Value(PLAYER_XP, fields[7].GetUInt32()); - _LoadIntoDataField(fields[61].GetCString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE); - _LoadIntoDataField(fields[64].GetCString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2); + _LoadIntoDataField(fields[66].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE); + _LoadIntoDataField(fields[69].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE * 2); SetObjectScale(1.0f); SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); @@ -16866,47 +16960,53 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) money = MAX_MONEY_AMOUNT; SetMoney(money); - SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32()); - SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32()); - SetByteValue(PLAYER_BYTES_3, 0, fields[5].GetUInt8()); - SetByteValue(PLAYER_BYTES_3, 1, fields[49].GetUInt8()); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID, fields[9].GetUInt8()); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID, fields[10].GetUInt8()); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID, fields[11].GetUInt8()); + SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID, fields[12].GetUInt8()); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE, fields[13].GetUInt8()); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS, fields[14].GetUInt8()); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE, fields[15].GetUInt8()); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER, fields[5].GetUInt8()); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION, fields[54].GetUInt8()); if (!ValidateAppearance( fields[3].GetUInt8(), // race fields[4].GetUInt8(), // class - gender, GetByteValue(PLAYER_BYTES, 2), // hair type - GetByteValue(PLAYER_BYTES, 3), //hair color - uint8(fields[9].GetUInt32() >> 8), // face - GetByteValue(PLAYER_BYTES_2, 0), // facial hair - GetByteValue(PLAYER_BYTES, 0))) // skin color - { - TC_LOG_ERROR("entities.player", "Player %s has wrong Appearance values (Hair/Skin/Color), can't be loaded.", guid.ToString().c_str()); + gender, + GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID), + GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID), + GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID), + GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE), + GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID))) + { + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has wrong Appearance values (Hair/Skin/Color), can't load.", guid.ToString().c_str()); return false; } - SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32()); - SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetUInt32()); + SetUInt32Value(PLAYER_FLAGS, fields[16].GetUInt32()); + SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[53].GetUInt32()); - SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64()); + SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[52].GetUInt64()); - SetUInt32Value(PLAYER_AMMO_ID, fields[63].GetUInt32()); + SetUInt32Value(PLAYER_AMMO_ID, fields[68].GetUInt32()); // set which actionbars the client has active - DO NOT REMOVE EVER AGAIN (can be changed though, if it does change fieldwise) - SetByteValue(PLAYER_FIELD_BYTES, 2, fields[65].GetUInt8()); + SetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES, fields[70].GetUInt8()); InitDisplayIds(); - // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory) + // cleanup inventory related item value fields (it will be filled correctly in _LoadInventory) for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) { SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty); - SetVisibleItemSlot(slot, NULL); + SetVisibleItemSlot(slot, nullptr); delete m_items[slot]; - m_items[slot] = NULL; + m_items[slot] = nullptr; } - TC_LOG_DEBUG("entities.player.loading", "Load Basic value of player %s is: ", m_name.c_str()); + TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: Load Basic value of player '%s' is: ", m_name.c_str()); outDebugValues(); //Need to call it to initialize m_team (m_team can be calculated from race) @@ -16920,21 +17020,21 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) InitPrimaryProfessions(); // to max set before any spell loaded // init saved position, and fix it later if problematic - ObjectGuid::LowType transLowGUID = fields[30].GetUInt32(); - Relocate(fields[12].GetFloat(), fields[13].GetFloat(), fields[14].GetFloat(), fields[16].GetFloat()); - uint32 mapId = fields[15].GetUInt16(); - uint32 instanceId = fields[58].GetUInt32(); + ObjectGuid::LowType transLowGUID = fields[35].GetUInt32(); + Relocate(fields[17].GetFloat(), fields[18].GetFloat(), fields[19].GetFloat(), fields[21].GetFloat()); + uint32 mapId = fields[20].GetUInt16(); + uint32 instanceId = fields[63].GetUInt32(); - uint32 dungeonDiff = fields[38].GetUInt8() & 0x0F; + uint32 dungeonDiff = fields[43].GetUInt8() & 0x0F; if (dungeonDiff >= MAX_DUNGEON_DIFFICULTY) dungeonDiff = DUNGEON_DIFFICULTY_NORMAL; - uint32 raidDiff = (fields[38].GetUInt8() >> 4) & 0x0F; + uint32 raidDiff = (fields[43].GetUInt8() >> 4) & 0x0F; if (raidDiff >= MAX_RAID_DIFFICULTY) raidDiff = RAID_DIFFICULTY_10MAN_NORMAL; SetDungeonDifficulty(Difficulty(dungeonDiff)); // may be changed in _LoadGroup SetRaidDifficulty(Difficulty(raidDiff)); // may be changed in _LoadGroup - std::string taxi_nodes = fields[37].GetString(); + std::string taxi_nodes = fields[42].GetString(); #define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); } @@ -16942,7 +17042,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) _LoadArenaTeamInfo(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ARENA_INFO)); - SetArenaPoints(fields[39].GetUInt32()); + SetArenaPoints(fields[44].GetUInt32()); // check arena teams integrity for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) @@ -16960,12 +17060,12 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0); } - SetHonorPoints(fields[40].GetUInt32()); - SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32()); - SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32()); - SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[43].GetUInt32()); - SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16()); - SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16()); + SetHonorPoints(fields[45].GetUInt32()); + SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[46].GetUInt32()); + SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[47].GetUInt32()); + SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[48].GetUInt32()); + SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[49].GetUInt16()); + SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[50].GetUInt16()); _LoadBoundInstances(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES)); _LoadInstanceTimeRestrictions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES)); @@ -16975,14 +17075,14 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); if (!mapEntry || !IsPositionValid()) { - TC_LOG_ERROR("entities.player", "Player %s have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid.ToString().c_str(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); RelocateToHomebind(); } // Player was saved in Arena or Bg else if (mapEntry && mapEntry->IsBattlegroundOrArena()) { - Battleground* currentBg = NULL; + Battleground* currentBg = nullptr; if (m_bgData.bgInstanceID) //saved in Battleground currentBg = sBattlegroundMgr->GetBattleground(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE); @@ -17016,7 +17116,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) //if (mapId == MAPID_INVALID) -- code kept for reference if (int16(mapId) == int16(-1)) // Battleground Entry Point not found (???) { - TC_LOG_ERROR("entities.player", "Player %s was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) was in BG in database, but BG was not found and entry point was invalid! Teleport to default race/class locations.", guid.ToString().c_str()); RelocateToHomebind(); } @@ -17032,13 +17132,13 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) { ObjectGuid transGUID(HighGuid::Mo_Transport, transLowGUID); - Transport* transport = NULL; + Transport* transport = nullptr; if (Transport* go = HashMapHolder<Transport>::Find(transGUID)) transport = go; if (transport) { - float x = fields[26].GetFloat(), y = fields[27].GetFloat(), z = fields[28].GetFloat(), o = fields[29].GetFloat(); + float x = fields[31].GetFloat(), y = fields[32].GetFloat(), z = fields[33].GetFloat(), o = fields[34].GetFloat(); m_movementInfo.transport.pos.Relocate(x, y, z, o); transport->CalculatePassengerPosition(x, y, z, &o); @@ -17048,7 +17148,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) std::fabs(m_movementInfo.transport.pos.GetPositionY()) > 250.0f || std::fabs(m_movementInfo.transport.pos.GetPositionZ()) > 250.0f) { - TC_LOG_ERROR("entities.player", "Player %s have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to bind location.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to bind location.", guid.ToString().c_str(), x, y, z, o); m_movementInfo.transport.Reset(); @@ -17065,7 +17165,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) } else { - TC_LOG_ERROR("entities.player", "Player %s have problems with transport guid (%u). Teleport to bind location.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has problems with transport guid (%u). Teleport to bind location.", guid.ToString().c_str(), transLowGUID); RelocateToHomebind(); @@ -17085,18 +17185,18 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam())) { // problems with taxi path loading - TaxiNodesEntry const* nodeEntry = NULL; + TaxiNodesEntry const* nodeEntry = nullptr; if (uint32 node_id = m_taxi.GetTaxiSource()) nodeEntry = sTaxiNodesStore.LookupEntry(node_id); - if (!nodeEntry) // don't know taxi start node, to homebind + if (!nodeEntry) // don't know taxi start node, teleport to homebind { - TC_LOG_ERROR("entities.player", "Character %u have wrong data in taxi destination list, teleport to homebind.", GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has wrong data in taxi destination list, teleport to homebind.", GetGUID().ToString().c_str()); RelocateToHomebind(); } - else // have start node, to it + else // has start node, teleport to it { - TC_LOG_ERROR("entities.player", "Character %u have too short taxi destination list, teleport to original node.", GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) has too short taxi destination list, teleport to original node.", GetGUID().ToString().c_str()); mapId = nodeEntry->map_id; Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z, 0.0f); } @@ -17125,7 +17225,8 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) { if (GetSession()->Expansion() < mapEntry->Expansion()) { - TC_LOG_DEBUG("entities.player.loading", "Player %s using client without required expansion tried login at non accessible map %u", GetName().c_str(), mapId); + TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: Player '%s' (%s) using client without required expansion tried login at non accessible map %u", + GetName().c_str(), GetGUID().ToString().c_str(), mapId); RelocateToHomebind(); } @@ -17139,7 +17240,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) // NOW player must have valid map // load the player's map here if it's not already loaded Map* map = sMapMgr->CreateMap(mapId, this, instanceId); - AreaTrigger const* areaTrigger = NULL; + AreaTrigger const* areaTrigger = nullptr; bool check = false; if (!map) @@ -17194,10 +17295,10 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) } else { - TC_LOG_ERROR("entities.player", "Player %s %s Map: %u, X: %f, Y: %f, Z: %f, O: %f. Areatrigger not found.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player '%s' (%s) Map: %u, X: %f, Y: %f, Z: %f, O: %f. Areatrigger not found.", m_name.c_str(), guid.ToString().c_str(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); RelocateToHomebind(); - map = NULL; + map = nullptr; } } @@ -17208,7 +17309,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) map = sMapMgr->CreateMap(mapId, this); if (!map) { - TC_LOG_ERROR("entities.player", "Player %s %s Map: %u, X: %f, Y: %f, Z: %f, O: %f. Invalid default map coordinates or instance couldn't be created.", + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player '%s' (%s) Map: %u, X: %f, Y: %f, Z: %f, O: %f. Invalid default map coordinates or instance couldn't be created.", m_name.c_str(), guid.ToString().c_str(), mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); return false; } @@ -17223,12 +17324,12 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE] // this must help in case next save after mass player load after server startup - m_nextSave = urand(m_nextSave/2, m_nextSave*3/2); + m_nextSave = urand(m_nextSave / 2, m_nextSave * 3 / 2); SaveRecallPosition(); - time_t now = time(NULL); - time_t logoutTime = time_t(fields[22].GetUInt32()); + time_t now = time(nullptr); + time_t logoutTime = time_t(fields[27].GetUInt32()); // since last logout (in seconds) uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference. @@ -17241,29 +17342,30 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) SetDrunkValue(newDrunkValue); - m_cinematic = fields[18].GetUInt8(); - m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32(); - m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32(); + m_cinematic = fields[23].GetUInt8(); + m_Played_time[PLAYED_TIME_TOTAL] = fields[24].GetUInt32(); + m_Played_time[PLAYED_TIME_LEVEL] = fields[25].GetUInt32(); - m_resetTalentsCost = fields[24].GetUInt32(); - m_resetTalentsTime = time_t(fields[25].GetUInt32()); + m_resetTalentsCost = fields[29].GetUInt32(); + m_resetTalentsTime = time_t(fields[30].GetUInt32()); - m_taxi.LoadTaxiMask(fields[17].GetString()); // must be before InitTaxiNodesForLevel + m_taxi.LoadTaxiMask(fields[22].GetString()); // must be before InitTaxiNodesForLevel - uint32 extraflags = fields[31].GetUInt16(); + uint32 extraflags = fields[36].GetUInt16(); - m_stableSlots = fields[32].GetUInt8(); + m_stableSlots = fields[37].GetUInt8(); if (m_stableSlots > MAX_PET_STABLES) { - TC_LOG_ERROR("entities.player", "Player can have not more %u stable slots, but have in DB %u", MAX_PET_STABLES, uint32(m_stableSlots)); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) can't have more stable slots than %u, but has %u in DB", + GetGUID().ToString().c_str(), MAX_PET_STABLES, uint32(m_stableSlots)); m_stableSlots = MAX_PET_STABLES; } - m_atLoginFlags = fields[33].GetUInt16(); + m_atLoginFlags = fields[38].GetUInt16(); if (HasAtLoginFlag(AT_LOGIN_RENAME)) { - TC_LOG_ERROR("entities.player", "Player (GUID: %u) tried to login while forced to rename, can't load.'", GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player (%s) tried to login while forced to rename, can't load.'", GetGUID().ToString().c_str()); return false; } @@ -17272,7 +17374,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) m_lastHonorUpdateTime = logoutTime; UpdateHonorFields(); - m_deathExpireTime = time_t(fields[36].GetUInt32()); + m_deathExpireTime = time_t(fields[41].GetUInt32()); if (m_deathExpireTime > now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP) m_deathExpireTime = now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP - 1; @@ -17309,7 +17411,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) InitRunes(); // rest bonus can only be calculated after InitStatsForLevel() - m_rest_bonus = fields[21].GetFloat(); + m_rest_bonus = fields[26].GetFloat(); if (time_diff > 0) { @@ -17317,11 +17419,11 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) float bubble0 = 0.031f; //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour) float bubble1 = 0.125f; - float bubble = fields[23].GetUInt8() > 0 + float bubble = fields[28].GetUInt8() > 0 ? bubble1*sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY) : bubble0*sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS); - SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble); + SetRestBonus(GetRestBonus() + time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 72000)*bubble); } // load skills after InitStatsForLevel because it triggering aura apply also @@ -17333,14 +17435,15 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) //mails are loaded only when needed ;-) - when player in game click on mailbox. //_LoadMail(); - m_specsCount = fields[59].GetUInt8(); - m_activeSpec = fields[60].GetUInt8(); + m_specsCount = fields[64].GetUInt8(); + m_activeSpec = fields[65].GetUInt8(); // sanity check if (m_specsCount > MAX_TALENT_SPECS || m_activeSpec > MAX_TALENT_SPEC || m_specsCount < MIN_TALENT_SPECS) { + TC_LOG_ERROR("entities.player", "Player::LoadFromDB: Player %s (%s) has invalid SpecCount = %u and/or invalid ActiveSpec = %u.", + GetName().c_str(), GetGUID().ToString().c_str(), uint32(m_specsCount), uint32(m_activeSpec)); m_activeSpec = 0; - TC_LOG_ERROR("entities.player", "Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName().c_str(), GetGUID().GetCounter(), m_specsCount, m_activeSpec); } _LoadTalents(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_TALENTS)); @@ -17384,7 +17487,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded - uint32 curTitle = fields[46].GetUInt32(); + uint32 curTitle = fields[51].GetUInt32(); if (curTitle && !HasTitle(curTitle)) curTitle = 0; @@ -17407,15 +17510,15 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) UpdateAllStats(); // restore remembered power/health values (but not more max values) - uint32 savedHealth = fields[50].GetUInt32(); + uint32 savedHealth = fields[55].GetUInt32(); SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth); for (uint8 i = 0; i < MAX_POWERS; ++i) { - uint32 savedPower = fields[51+i].GetUInt32(); + uint32 savedPower = fields[56 + i].GetUInt32(); SetPower(Powers(i), savedPower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower); } - TC_LOG_DEBUG("entities.player.loading", "The value of player %s after load item and aura is: ", m_name.c_str()); + TC_LOG_DEBUG("entities.player.loading", "Player::LoadFromDB: The value of player '%s' after load item and aura is: ", m_name.c_str()); outDebugValues(); // GM state @@ -17467,12 +17570,12 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) } // RaF stuff. - m_grantableLevels = fields[66].GetUInt8(); + m_grantableLevels = fields[71].GetUInt8(); if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0)) SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND); if (m_grantableLevels > 0) - SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01); + SetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01); _LoadDeclinedNames(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES)); @@ -17494,6 +17597,8 @@ bool Player::isAllowedToLoot(const Creature* creature) const Loot* loot = &creature->loot; if (loot->isLooted()) // nothing to loot or everything looted. return false; + if (!loot->hasItemForAll() && !loot->hasItemFor(this)) // no loot in creature for this player + return false; if (loot->loot_type == LOOT_SKINNING) return creature->GetSkinner() == GetGUID(); @@ -17550,9 +17655,10 @@ void Player::_LoadActions(PreparedQueryResult result) ab->uState = ACTIONBUTTON_UNCHANGED; else { - TC_LOG_ERROR("entities.player", " ...at loading, and will deleted in DB also"); + TC_LOG_DEBUG("entities.player", "Player::_LoadActions: Player '%s' (%s) has an invalid action button (Button: %u, Action: %u, Type: %u). It will be deleted at next save. This can be due to a player changing their talents.", + GetName().c_str(), GetGUID().ToString().c_str(), button, action, type); - // Will deleted in DB at next save (it can create data until save but marked as deleted) + // Will be deleted in DB at next save (it can create data until save but marked as deleted). m_actionButtons[button].uState = ACTIONBUTTON_DELETED; } } while (result->NextRow()); @@ -17561,7 +17667,7 @@ void Player::_LoadActions(PreparedQueryResult result) void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) { - TC_LOG_DEBUG("entities.player.loading", "Loading auras for player %u", GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadAuras: Loading auras for %s", GetGUID().ToString().c_str()); /* 0 1 2 3 4 5 6 7 8 9 10 QueryResult* result = CharacterDatabase.PQuery("SELECT casterGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, @@ -17594,7 +17700,8 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid); if (!spellInfo) { - TC_LOG_ERROR("entities.player", "Unknown aura (spellid %u), ignore.", spellid); + TC_LOG_ERROR("entities.player", "Player::_LoadAuras: Player '%s' (%s) has an invalid aura (SpellID: %u), ignoring.", + GetName().c_str(), GetGUID().ToString().c_str(), spellid); continue; } @@ -17618,7 +17725,7 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) else remaincharges = 0; - if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, NULL, &baseDamage[0], NULL, caster_guid)) + if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, nullptr, &baseDamage[0], nullptr, caster_guid)) { if (!aura->CanBeSaved()) { @@ -17628,7 +17735,8 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) aura->SetLoadedState(maxduration, remaintime, remaincharges, stackcount, recalculatemask, &damage[0]); aura->ApplyForTargets(); - TC_LOG_DEBUG("entities.player", "Added aura spellid %u, effectmask %u", spellInfo->Id, effmask); + TC_LOG_DEBUG("entities.player", "Player::_LoadAuras: Added aura (SpellID: %u, EffectMask: %u) to player '%s (%s)", + spellInfo->Id, effmask, GetName().c_str(), GetGUID().ToString().c_str()); } } while (result->NextRow()); @@ -17651,13 +17759,13 @@ void Player::_LoadGlyphAuras() continue; } else - TC_LOG_ERROR("entities.player", "Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags); + TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '%s' (%s) has glyph with typeflags %u in slot with typeflags %u, removing.", GetName().c_str(), GetGUID().ToString().c_str(), gp->TypeFlags, gs->TypeFlags); } else - TC_LOG_ERROR("entities.player", "Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i); + TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '%s' (%s) has not existing glyph slot entry %u on index %u", GetName().c_str(), GetGUID().ToString().c_str(), GetGlyphSlot(i), i); } else - TC_LOG_ERROR("entities.player", "Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i); + TC_LOG_ERROR("entities.player", "Player::_LoadGlyphAuras: Player '%s' (%s) has not existing glyph entry %u on index %u", GetName().c_str(), GetGUID().ToString().c_str(), glyph, i); // On any error remove glyph SetGlyph(i, 0); @@ -17676,7 +17784,7 @@ void Player::LoadCorpse(PreparedQueryResult result) { Field* fields = result->Fetch(); _corpseLocation.WorldRelocate(fields[0].GetUInt16(), fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); - ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(_corpseLocation.GetMapId())->Instanceable()); + ApplyModByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_FLAGS, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(_corpseLocation.GetMapId())->Instanceable()); } else ResurrectPlayer(0.5f); @@ -17712,11 +17820,11 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) ObjectGuid::LowType bagGuid = fields[11].GetUInt32(); uint8 slot = fields[12].GetUInt8(); - uint8 err = EQUIP_ERR_OK; + InventoryResult err = EQUIP_ERR_OK; // Item is not in bag if (!bagGuid) { - item->SetContainer(NULL); + item->SetContainer(nullptr); item->SetSlot(slot); if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot)) @@ -17773,8 +17881,8 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) } else { - TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which doesnt have a valid bag (Bag GUID: %u, slot: %u). Possible cheat?", - GetGUID().GetCounter(), GetName().c_str(), item->GetGUID().GetCounter(), item->GetEntry(), bagGuid, slot); + TC_LOG_ERROR("entities.player", "Player::_LoadInventory: Player '%s' (%s) has item (%s, entry: %u) which doesnt have a valid bag (Bag %u, slot: %u). Possible cheat?", + GetName().c_str(), GetGUID().ToString().c_str(), item->GetGUID().ToString().c_str(), item->GetEntry(), bagGuid, slot); item->DeleteFromInventoryDB(trans); delete item; continue; @@ -17787,8 +17895,8 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) item->SetState(ITEM_UNCHANGED, this); else { - TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which can't be loaded into inventory (Bag GUID: %u, slot: %u) by reason %u. Item will be sent by mail.", - GetGUID().GetCounter(), GetName().c_str(), item->GetGUID().GetCounter(), item->GetEntry(), bagGuid, slot, err); + TC_LOG_ERROR("entities.player", "Player::_LoadInventory: Player '%s' (%s) has item (%s, entry: %u) which can't be loaded into inventory (Bag %u, slot: %u) by reason %u. Item will be sent by mail.", + GetName().c_str(), GetGUID().ToString().c_str(), item->GetGUID().ToString().c_str(), item->GetEntry(), bagGuid, slot, uint32(err)); item->DeleteFromInventoryDB(trans); problematicItems.push_back(item); } @@ -17818,7 +17926,7 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields) { - Item* item = NULL; + Item* item = nullptr; ObjectGuid::LowType itemGuid = fields[13].GetUInt32(); uint32 itemEntry = fields[14].GetUInt32(); if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry)) @@ -17827,7 +17935,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F item = NewItemOrBag(proto); if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry)) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; // Do not allow to have item limited to another map/zone in alive state if (IsAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId)) @@ -17920,7 +18028,7 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F } else { - TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has broken item (GUID: %u, entry: %u) in inventory. Deleting item.", + TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has a broken item (GUID: %u, entry: %u) in inventory. Deleting item.", GetGUID().GetCounter(), GetName().c_str(), itemGuid, itemEntry); remove = true; } @@ -17930,12 +18038,12 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F Item::DeleteFromInventoryDB(trans, itemGuid); item->FSetState(ITEM_REMOVED); item->SaveToDB(trans); // it also deletes item object! - item = NULL; + item = nullptr; } } else { - TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has unknown item (entry: %u) in inventory. Deleting item.", + TC_LOG_ERROR("entities.player", "Player::_LoadInventory: player (GUID: %u, name: '%s') has an unknown item (entry: %u) in inventory. Deleting item.", GetGUID().GetCounter(), GetName().c_str(), itemEntry); Item::DeleteFromInventoryDB(trans, itemGuid); Item::DeleteFromDB(trans, itemGuid); @@ -17966,7 +18074,8 @@ void Player::_LoadMailedItems(Mail* mail) if (!proto) { - TC_LOG_ERROR("entities.player", "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUID().GetCounter(), itemGuid, itemTemplate, mail->messageID); + TC_LOG_ERROR("entities.player", "Player '%s' (%s) has unknown item_template in mailed items (GUID: %u, Entry: %u) in mail (%u), deleted.", + GetName().c_str(), GetGUID().ToString().c_str(), itemGuid, itemTemplate, mail->messageID); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM); stmt->setUInt32(0, itemGuid); @@ -17982,7 +18091,7 @@ void Player::_LoadMailedItems(Mail* mail) if (!item->LoadFromDB(itemGuid, ObjectGuid(HighGuid::Player, fields[13].GetUInt32()), fields, itemTemplate)) { - TC_LOG_ERROR("entities.player", "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, itemGuid); + TC_LOG_ERROR("entities.player", "Player::_LoadMailedItems: Item (GUID: %u) in mail (%u) doesn't exist, deleted from mail.", itemGuid, mail->messageID); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM); stmt->setUInt32(0, itemGuid); @@ -17990,7 +18099,7 @@ void Player::_LoadMailedItems(Mail* mail) item->FSetState(ITEM_REMOVED); - SQLTransaction temp = SQLTransaction(NULL); + SQLTransaction temp = SQLTransaction(nullptr); item->SaveToDB(temp); // it also deletes item object ! continue; } @@ -18045,7 +18154,7 @@ void Player::_LoadMail() if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId)) { - TC_LOG_ERROR("entities.player", "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId); + TC_LOG_ERROR("entities.player", "Player::_LoadMail: Mail (%u) has nonexistent MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId); m->mailTemplateId = 0; } @@ -18102,8 +18211,8 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) else { questStatusData.Status = QUEST_STATUS_INCOMPLETE; - TC_LOG_ERROR("entities.player", "Player %s (GUID: %u) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).", - GetName().c_str(), GetGUID().GetCounter(), quest_id, qstatus); + TC_LOG_ERROR("entities.player", "Player::_LoadQuestStatus: Player '%s' (%s) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).", + GetName().c_str(), GetGUID().ToString().c_str(), quest_id, qstatus); } questStatusData.Explored = (fields[2].GetUInt8() > 0); @@ -18152,7 +18261,8 @@ void Player::_LoadQuestStatus(PreparedQueryResult result) ++slot; } - TC_LOG_DEBUG("entities.player.loading", "Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.Status, quest_id, GetGUID().GetCounter()); + + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadQuestStatus: Quest status is {%u} for quest {%u} for player (%s)", questStatusData.Status, quest_id, GetGUID().ToString().c_str()); } } while (result->NextRow()); @@ -18190,9 +18300,10 @@ void Player::_LoadQuestStatusRewarded(PreparedQueryResult result) if (quest->GetBonusTalents()) m_questRewardTalentCount += quest->GetBonusTalents(); - } - m_RewardedQuests.insert(quest_id); + if (quest->CanIncreaseRewardedQuestCounters()) + m_RewardedQuests.insert(quest_id); + } } while (result->NextRow()); } @@ -18226,7 +18337,7 @@ void Player::_LoadDailyQuestStatus(PreparedQueryResult result) if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query { - TC_LOG_ERROR("entities.player", "Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`", GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player (GUID: %u) has more than 25 daily quest records in `charcter_queststatus_daily`", GetGUID().GetCounter()); break; } @@ -18242,7 +18353,8 @@ void Player::_LoadDailyQuestStatus(PreparedQueryResult result) SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx, quest_id); ++quest_daily_idx; - TC_LOG_DEBUG("entities.player.loading", "Daily quest (%u) cooldown for player (GUID: %u)", quest_id, GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadDailyQuestStatus: Loaded daily quest cooldown (QuestID: %u) for player '%s' (%s)", + quest_id, GetName().c_str(), GetGUID().ToString().c_str()); } while (result->NextRow()); } @@ -18265,7 +18377,9 @@ void Player::_LoadWeeklyQuestStatus(PreparedQueryResult result) continue; m_weeklyquests.insert(quest_id); - TC_LOG_DEBUG("entities.player.loading", "Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUID().GetCounter()); + + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadWeeklyQuestStatus: Loaded weekly quest cooldown (QuestID: %u) for player '%s' (%s)", + quest_id, GetName().c_str(), GetGUID().ToString().c_str()); } while (result->NextRow()); } @@ -18289,7 +18403,8 @@ void Player::_LoadSeasonalQuestStatus(PreparedQueryResult result) continue; m_seasonalquests[event_id].insert(quest_id); - TC_LOG_DEBUG("entities.player.loading", "Seasonal quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadSeasonalQuestStatus: Loaded seasonal quest cooldown (QuestID: %u) for player '%s' (%s)", + quest_id, GetName().c_str(), GetGUID().ToString().c_str()); } while (result->NextRow()); } @@ -18312,7 +18427,8 @@ void Player::_LoadMonthlyQuestStatus(PreparedQueryResult result) continue; m_monthlyquests.insert(quest_id); - TC_LOG_DEBUG("entities.player.loading", "Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.player.loading", "Player::_LoadMonthlyQuestStatus: Loaded monthly quest cooldown (QuestID: %u) for player '%s' (%s)", + quest_id, GetName().c_str(), GetGUID().ToString().c_str()); } while (result->NextRow()); } @@ -18389,12 +18505,14 @@ void Player::_LoadBoundInstances(PreparedQueryResult result) if (!mapEntry || !mapEntry->IsDungeon()) { - TC_LOG_ERROR("entities.player", "_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d (%s)", GetName().c_str(), GetGUID().GetCounter(), mapId, mapname.c_str()); + TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: Player '%s' (%s) has bind to not existed or not dungeon map %d (%s)", + GetName().c_str(), GetGUID().ToString().c_str(), mapId, mapname.c_str()); deleteInstance = true; } else if (difficulty >= MAX_DIFFICULTY) { - TC_LOG_ERROR("entities.player", "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u (%s)", GetName().c_str(), GetGUID().GetCounter(), difficulty, mapId, mapname.c_str()); + TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) has bind to not existed difficulty %d instance for map %u (%s)", + GetName().c_str(), GetGUID().ToString().c_str(), difficulty, mapId, mapname.c_str()); deleteInstance = true; } else @@ -18402,12 +18520,14 @@ void Player::_LoadBoundInstances(PreparedQueryResult result) MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(difficulty)); if (!mapDiff) { - TC_LOG_ERROR("entities.player", "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u (%s)", GetName().c_str(), GetGUID().GetCounter(), difficulty, mapId, mapname.c_str()); + TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) has bind to not existed difficulty %d instance for map %u (%s)", + GetName().c_str(), GetGUID().ToString().c_str(), difficulty, mapId, mapname.c_str()); deleteInstance = true; } else if (!perm && group) { - TC_LOG_ERROR("entities.player", "_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d (%s), %d, %d", GetName().c_str(), GetGUID().GetCounter(), group->GetLowGUID(), mapId, mapname.c_str(), instanceId, difficulty); + TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) is in group %s but has a non-permanent character bind to map %d (%s), %d, %d", + GetName().c_str(), GetGUID().ToString().c_str(), group->GetGUID().ToString().c_str(), mapId, mapname.c_str(), instanceId, difficulty); deleteInstance = true; } } @@ -18437,7 +18557,7 @@ InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty // some instances only have one difficulty MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty); if (!mapDiff) - return NULL; + return nullptr; BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); if (itr != m_boundInstances[difficulty].end()) @@ -18543,12 +18663,13 @@ InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, B bind.perm = permanent; bind.extendState = extendState; if (!load) - TC_LOG_DEBUG("maps", "Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName().c_str(), GetGUID().GetCounter(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty()); - sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficulty(), save->GetMapId(), permanent, uint8(extendState)); + TC_LOG_DEBUG("maps", "Player::BindToInstance: Player '%s' (%s) is now bound to map (ID: %d, Instance: %d, Difficulty: %d)", + GetName().c_str(), GetGUID().ToString().c_str(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty()); + sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficulty(), save->GetMapId(), permanent, extendState); return &bind; } - return NULL; + return nullptr; } void Player::BindToInstance() @@ -18582,7 +18703,7 @@ void Player::SendRaidInfo() size_t p_counter = data.wpos(); data << uint32(counter); // placeholder - time_t now = time(NULL); + time_t now = time(nullptr); for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { @@ -18741,7 +18862,7 @@ bool Player::CheckInstanceValidity(bool /*isLogin*/) return true; // non-instances are always valid - Map* map = GetMap(); + Map* map = FindMap(); if (!map || !map->IsDungeon()) return true; @@ -18805,7 +18926,8 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass()); if (!info) { - TC_LOG_ERROR("entities.player", "Player (Name %s) has incorrect race/class pair. Can't be loaded.", GetName().c_str()); + TC_LOG_ERROR("entities.player", "Player::_LoadHomeBind: Player '%s' (%s) has incorrect race/class (%u/%u) pair. Can't load.", + GetGUID().ToString().c_str(), GetName().c_str(), uint32(getRace()), uint32(getClass())); return false; } @@ -18853,8 +18975,8 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) CharacterDatabase.Execute(stmt); } - TC_LOG_DEBUG("entities.player", "Setting player home position - mapid: %u, areaid: %u, X: %f, Y: %f, Z: %f", - m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ); + TC_LOG_DEBUG("entities.player", "Player::_LoadHomeBind: Setting home position (MapID: %u, AreaID: %u, X: %f, Y: %f, Z: %f) of player '%s' (%s)", + m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetName().c_str(), GetGUID().ToString().c_str()); return true; } @@ -18878,13 +19000,13 @@ void Player::SaveToDB(bool create /*=false*/) // first save/honor gain after midnight will also update the player's honor fields UpdateHonorFields(); - TC_LOG_DEBUG("entities.unit", "The value of player %s at save: ", m_name.c_str()); + TC_LOG_DEBUG("entities.unit", "Player::SaveToDB: The value of player %s at save: ", m_name.c_str()); outDebugValues(); if (!create) sScriptMgr->OnPlayerSave(this); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; uint8 index = 0; if (create) @@ -18897,12 +19019,17 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setString(index++, GetName()); stmt->setUInt8(index++, getRace()); stmt->setUInt8(index++, getClass()); - stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_3, 0)); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER)); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect stmt->setUInt8(index++, getLevel()); stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP)); stmt->setUInt32(index++, GetMoney()); - stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES)); - stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE)); stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS)); stmt->setUInt16(index++, (uint16)GetMapId()); stmt->setUInt32(index++, (uint32)GetInstanceId()); @@ -18927,7 +19054,7 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]); stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]); stmt->setFloat(index++, finiteAlways(m_rest_bonus)); - stmt->setUInt32(index++, uint32(time(NULL))); + stmt->setUInt32(index++, uint32(time(nullptr))); stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0)); //save, far from tavern/city //save, but in tavern/city @@ -18992,8 +19119,8 @@ void Player::SaveToDB(bool create /*=false*/) ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' '; stmt->setString(index++, ss.str()); - stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, 2)); - stmt->setUInt32(index++, m_grantableLevels); + stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES)); + stmt->setUInt32(index, m_grantableLevels); } else { @@ -19002,12 +19129,17 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setString(index++, GetName()); stmt->setUInt8(index++, getRace()); stmt->setUInt8(index++, getClass()); - stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_3, 0)); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER)); // save gender from PLAYER_BYTES_3, UNIT_BYTES_0 changes with every transform effect stmt->setUInt8(index++, getLevel()); stmt->setUInt32(index++, GetUInt32Value(PLAYER_XP)); stmt->setUInt32(index++, GetMoney()); - stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES)); - stmt->setUInt32(index++, GetUInt32Value(PLAYER_BYTES_2)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS)); + stmt->setUInt8(index++, GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE)); stmt->setUInt32(index++, GetUInt32Value(PLAYER_FLAGS)); if (!IsBeingTeleported()) @@ -19047,7 +19179,7 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]); stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]); stmt->setFloat(index++, finiteAlways(m_rest_bonus)); - stmt->setUInt32(index++, uint32(time(NULL))); + stmt->setUInt32(index++, uint32(time(nullptr))); stmt->setUInt8(index++, (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0)); //save, far from tavern/city //save, but in tavern/city @@ -19112,7 +19244,7 @@ void Player::SaveToDB(bool create /*=false*/) ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << ' '; stmt->setString(index++, ss.str()); - stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, 2)); + stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES)); stmt->setUInt32(index++, m_grantableLevels); stmt->setUInt8(index++, IsInWorld() && !GetSession()->PlayerLogout() ? 1 : 0); @@ -19166,7 +19298,7 @@ void Player::SaveInventoryAndGoldToDB(SQLTransaction& trans) SaveGoldToDB(trans); } -void Player::SaveGoldToDB(SQLTransaction& trans) +void Player::SaveGoldToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_MONEY); stmt->setUInt32(0, GetMoney()); @@ -19176,7 +19308,7 @@ void Player::SaveGoldToDB(SQLTransaction& trans) void Player::_SaveActions(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();) { @@ -19280,7 +19412,7 @@ void Player::_SaveAuras(SQLTransaction& trans) void Player::_SaveInventory(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; // force items in buyback slots to new state // and remove those that aren't already for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i) @@ -19318,7 +19450,8 @@ void Player::_SaveInventory(SQLTransaction& trans) } else { - TC_LOG_ERROR("entities.player", "Can't find %s but is in refundable storage for player %u ! Removing.", itr->ToString().c_str(), GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Can't find item (%s) in refundable storage for player '%s' (%s), removing.", + itr->ToString().c_str(), GetName().c_str(), GetGUID().ToString().c_str()); m_refundableItems.erase(itr); } } @@ -19344,12 +19477,14 @@ void Player::_SaveInventory(SQLTransaction& trans) if (item->GetState() != ITEM_REMOVED) { Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot()); - if (test == NULL) + if (test == nullptr) { ObjectGuid::LowType bagTestGUID = 0; if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot())) bagTestGUID = test2->GetGUID().GetCounter(); - TC_LOG_ERROR("entities.player", "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u (state %d) are incorrect, the player doesn't have an item at that position!", lowGuid, GetName().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().GetCounter(), (int32)item->GetState()); + + TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Player '%s' (%s) has incorrect values (Bag: %u, Slot: %u) for the item (%s, State: %d). The player doesn't have an item at that position.", + GetName().c_str(), GetGUID().ToString().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString().c_str(), (int32)item->GetState()); // according to the test that was just performed nothing should be in this slot, delete stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT); stmt->setUInt32(0, bagTestGUID); @@ -19365,9 +19500,10 @@ void Player::_SaveInventory(SQLTransaction& trans) } else if (test != item) { - TC_LOG_ERROR("entities.player", "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u are incorrect, the item with guid %u is there instead!", lowGuid, GetName().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().GetCounter(), test->GetGUID().GetCounter()); + TC_LOG_ERROR("entities.player", "Player::_SaveInventory: Player '%s' (%s) has incorrect values (Bag: %u, Slot: %u) for the item (%s). %s is there instead!", + GetName().c_str(), GetGUID().ToString().c_str(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString().c_str(), test->GetGUID().ToString().c_str()); // save all changes to the item... - if (item->GetState() != ITEM_NEW) // only for existing items, no dupes + if (item->GetState() != ITEM_NEW) // only for existing items, no duplicates item->SaveToDB(trans); // ...but do not save position in invntory continue; @@ -19404,7 +19540,7 @@ void Player::_SaveMail(SQLTransaction& trans) if (!m_mailsLoaded) return; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { @@ -19480,7 +19616,7 @@ void Player::_SaveQuestStatus(SQLTransaction& trans) QuestStatusSaveMap::iterator saveItr; QuestStatusMap::iterator statusItr; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS); @@ -19662,7 +19798,7 @@ void Player::_SaveMonthlyQuestStatus(SQLTransaction& trans) void Player::_SaveSkills(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; // we don't need transactions here. for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end();) { @@ -19718,7 +19854,7 @@ void Player::_SaveSkills(SQLTransaction& trans) void Player::_SaveSpells(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end();) { @@ -19756,13 +19892,13 @@ void Player::_SaveSpells(SQLTransaction& trans) // save player stats -- only for external usage // real stats will be recalculated on player login -void Player::_SaveStats(SQLTransaction& trans) +void Player::_SaveStats(SQLTransaction& trans) const { // check if stat saving is enabled and if char level is high enough if (!sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE)) return; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS); stmt->setUInt32(0, GetGUID().GetCounter()); @@ -19826,7 +19962,7 @@ void Player::UpdateSpeakTime() if (GetSession()->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHAT_SPAM)) return; - time_t current = time (NULL); + time_t current = time(nullptr); if (m_speakTime > current) { uint32 max_count = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT); @@ -19852,14 +19988,14 @@ void Player::UpdateSpeakTime() bool Player::CanSpeak() const { - return GetSession()->m_muteTime <= time (NULL); + return GetSession()->m_muteTime <= time (nullptr); } /*********************************************************/ /*** LOW LEVEL FUNCTIONS:Notifiers ***/ /*********************************************************/ -void Player::SendAttackSwingNotInRange() +void Player::SendAttackSwingNotInRange() const { WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0); GetSession()->SendPacket(&data); @@ -19893,48 +20029,38 @@ void Player::SetUInt32ValueInArray(Tokenizer& tokens, uint16 index, uint32 value void Player::Customize(CharacterCustomizeInfo const* customizeInfo, SQLTransaction& trans) { - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PLAYERBYTES2); - stmt->setUInt32(0, customizeInfo->Guid.GetCounter()); - PreparedQueryResult result = CharacterDatabase.Query(stmt); - - if (!result) - return; - - Field* fields = result->Fetch(); - - uint32 playerBytes2 = fields[0].GetUInt32(); - playerBytes2 &= ~0xFF; - playerBytes2 |= customizeInfo->FacialHair; - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_PLAYERBYTES); + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_AND_APPEARANCE); stmt->setUInt8(0, customizeInfo->Gender); - stmt->setUInt32(1, customizeInfo->Skin | (customizeInfo->Face << 8) | (customizeInfo->HairStyle << 16) | (customizeInfo->HairColor << 24)); - stmt->setUInt32(2, playerBytes2); - stmt->setUInt32(3, customizeInfo->Guid.GetCounter()); + stmt->setUInt8(1, customizeInfo->Skin); + stmt->setUInt8(2, customizeInfo->Face); + stmt->setUInt8(3, customizeInfo->HairStyle); + stmt->setUInt8(4, customizeInfo->HairColor); + stmt->setUInt8(5, customizeInfo->FacialHair); + stmt->setUInt32(6, customizeInfo->Guid.GetCounter()); CharacterDatabase.ExecuteOrAppend(trans, stmt); } -void Player::SendAttackSwingDeadTarget() +void Player::SendAttackSwingDeadTarget() const { WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0); GetSession()->SendPacket(&data); } -void Player::SendAttackSwingCantAttack() +void Player::SendAttackSwingCantAttack() const { WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0); GetSession()->SendPacket(&data); } -void Player::SendAttackSwingCancelAttack() +void Player::SendAttackSwingCancelAttack() const { WorldPacket data(SMSG_CANCEL_COMBAT, 0); GetSession()->SendPacket(&data); } -void Player::SendAttackSwingBadFacingAttack() +void Player::SendAttackSwingBadFacingAttack() const { WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0); GetSession()->SendPacket(&data); @@ -19947,7 +20073,7 @@ void Player::SendAutoRepeatCancel(Unit* target) SendMessageToSet(&data, false); } -void Player::SendExplorationExperience(uint32 Area, uint32 Experience) +void Player::SendExplorationExperience(uint32 Area, uint32 Experience) const { WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8); data << uint32(Area); @@ -19955,7 +20081,7 @@ void Player::SendExplorationExperience(uint32 Area, uint32 Experience) GetSession()->SendPacket(&data); } -void Player::SendDungeonDifficulty(bool IsInGroup) +void Player::SendDungeonDifficulty(bool IsInGroup) const { uint8 val = 0x00000001; WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12); @@ -19965,7 +20091,7 @@ void Player::SendDungeonDifficulty(bool IsInGroup) GetSession()->SendPacket(&data); } -void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) +void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const { uint8 val = 0x00000001; WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12); @@ -19975,7 +20101,7 @@ void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) GetSession()->SendPacket(&data); } -void Player::SendResetFailedNotify(uint32 mapid) +void Player::SendResetFailedNotify(uint32 mapid) const { WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4); data << uint32(mapid); @@ -20031,14 +20157,14 @@ void Player::ResetInstances(uint8 method, bool isRaid) } } -void Player::SendResetInstanceSuccess(uint32 MapId) +void Player::SendResetInstanceSuccess(uint32 MapId) const { WorldPacket data(SMSG_INSTANCE_RESET, 4); data << uint32(MapId); GetSession()->SendPacket(&data); } -void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) +void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const { /*reasons for instance reset failure: // 0: There are players inside the instance. @@ -20116,22 +20242,22 @@ Pet* Player::GetPet() const if (ObjectGuid pet_guid = GetPetGUID()) { if (!pet_guid.IsPet()) - return NULL; + return nullptr; Pet* pet = ObjectAccessor::GetPet(*this, pet_guid); if (!pet) - return NULL; + return nullptr; if (IsInWorld() && pet) return pet; - //there may be a guardian in slot - //TC_LOG_ERROR("entities.player", "Player::GetPet: Pet %u not exist.", GUID_LOPART(pet_guid)); + // there may be a guardian in this slot + //TC_LOG_ERROR("entities.player", "Player::GetPet: Pet %u does not exist.", GUID_LOPART(pet_guid)); //const_cast<Player*>(this)->SetPetGUID(0); } - return NULL; + return nullptr; } void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) @@ -20141,7 +20267,8 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) if (pet) { - TC_LOG_DEBUG("entities.pet", "RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent); + TC_LOG_DEBUG("entities.pet", "Player::RemovePet: Player '%s' (%s), Pet (Entry: %u, Mode: %u, ReturnReagent: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), pet->GetEntry(), mode, returnreagent); if (pet->m_removed) return; @@ -20226,7 +20353,7 @@ void Player::StopCastingCharm() if (charm->GetTypeId() == TYPEID_UNIT) { if (charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET)) - ((Puppet*)charm)->UnSummon(); + static_cast<Puppet*>(charm)->UnSummon(); else if (charm->IsVehicle()) ExitVehicle(); } @@ -20235,14 +20362,14 @@ void Player::StopCastingCharm() if (GetCharmGUID()) { - TC_LOG_FATAL("entities.player", "Player %s (%s) is not able to uncharm unit (%s)", GetName().c_str(), GetGUID().ToString().c_str(), GetCharmGUID().ToString().c_str()); - if (charm->GetCharmerGUID()) + TC_LOG_FATAL("entities.player", "Player::StopCastingCharm: Player '%s' (%s) is not able to uncharm unit (%s)", GetName().c_str(), GetGUID().ToString().c_str(), GetCharmGUID().ToString().c_str()); + if (!charm->GetCharmerGUID().IsEmpty()) { - TC_LOG_FATAL("entities.player", "Charmed unit has charmer %s", charm->GetCharmerGUID().ToString().c_str()); + TC_LOG_FATAL("entities.player", "Player::StopCastingCharm: Charmed unit has charmer %s", charm->GetCharmerGUID().ToString().c_str()); ABORT(); } - else - SetCharm(charm, false); + + SetCharm(charm, false); } } @@ -20256,6 +20383,11 @@ void Player::Say(std::string const& text, Language language, WorldObject const* SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true); } +void Player::Say(uint32 textId, WorldObject const* target /*= nullptr*/) +{ + Talk(textId, CHAT_MSG_SAY, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), target); +} + void Player::Yell(std::string const& text, Language language, WorldObject const* /*= nullptr*/) { std::string _text(text); @@ -20266,6 +20398,11 @@ void Player::Yell(std::string const& text, Language language, WorldObject const* SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), true); } +void Player::Yell(uint32 textId, WorldObject const* target /*= nullptr*/) +{ + Talk(textId, CHAT_MSG_YELL, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), target); +} + void Player::TextEmote(std::string const& text, WorldObject const* /*= nullptr*/, bool /*= false*/) { std::string _text(text); @@ -20276,6 +20413,11 @@ void Player::TextEmote(std::string const& text, WorldObject const* /*= nullptr*/ SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), true, !GetSession()->HasPermission(rbac::RBAC_PERM_TWO_SIDE_INTERACTION_CHAT)); } +void Player::TextEmote(uint32 textId, WorldObject const* target /*= nullptr*/, bool /*isBossEmote = false*/) +{ + Talk(textId, CHAT_MSG_EMOTE, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), target); +} + void Player::Whisper(std::string const& text, Language language, Player* target, bool /*= false*/) { ASSERT(target); @@ -20312,6 +20454,24 @@ void Player::Whisper(std::string const& text, Language language, Player* target, ChatHandler(GetSession()).PSendSysMessage(LANG_PLAYER_DND, target->GetName().c_str(), target->autoReplyMsg.c_str()); } +void Player::Whisper(uint32 textId, Player* target, bool /*isBossWhisper = false*/) +{ + if (!target) + return; + + BroadcastText const* bct = sObjectMgr->GetBroadcastText(textId); + if (!bct) + { + TC_LOG_ERROR("entities.unit", "WorldObject::MonsterWhisper: `broadcast_text` was not %u found", textId); + return; + } + + LocaleConstant locale = target->GetSession()->GetSessionDbLocaleIndex(); + WorldPacket data; + ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, LANG_UNIVERSAL, this, target, bct->GetText(locale, getGender()), 0, "", locale); + target->SendDirectMessage(&data); +} + Item* Player::GetMItem(uint32 id) { ItemMap::const_iterator itr = mMitems.find(id); @@ -20330,7 +20490,7 @@ bool Player::RemoveMItem(uint32 id) return mMitems.erase(id) ? true : false; } -void Player::SendOnCancelExpectedVehicleRideAura() +void Player::SendOnCancelExpectedVehicleRideAura() const { WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); GetSession()->SendPacket(&data); @@ -20395,7 +20555,7 @@ void Player::PossessSpellInitialize() if (!charmInfo) { - TC_LOG_ERROR("entities.player", "Player::PossessSpellInitialize(): charm (%s) has no charminfo!", charm->GetGUID().ToString().c_str()); + TC_LOG_ERROR("entities.player", "Player::PossessSpellInitialize: charm (%s) has no charminfo!", charm->GetGUID().ToString().c_str()); return; } @@ -20430,7 +20590,7 @@ void Player::VehicleSpellInitialize() data << uint8(0); // Command State data << uint16(0x800); // DisableActions (set for all vehicles) - for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint32 i = 0; i < MAX_CREATURE_SPELLS; ++i) { uint32 spellId = vehicle->m_spells[i]; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); @@ -20442,7 +20602,8 @@ void Player::VehicleSpellInitialize() if (!sConditionMgr->IsObjectMeetingVehicleSpellConditions(vehicle->GetEntry(), spellId, this, vehicle)) { - TC_LOG_DEBUG("condition", "VehicleSpellInitialize: conditions not met for Vehicle entry %u spell %u", vehicle->ToCreature()->GetEntry(), spellId); + TC_LOG_DEBUG("condition", "Player::VehicleSpellInitialize: Player '%s' (%s) doesn't meet conditions for vehicle (Entry: %u, Spell: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), vehicle->ToCreature()->GetEntry(), spellId); data << uint16(0) << uint8(0) << uint8(i+8); continue; } @@ -20453,7 +20614,7 @@ void Player::VehicleSpellInitialize() data << uint32(MAKE_UNIT_ACTION_BUTTON(spellId, i+8)); } - for (uint32 i = CREATURE_MAX_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i) + for (uint32 i = MAX_CREATURE_SPELLS; i < MAX_SPELL_CONTROL_BAR; ++i) data << uint32(0); data << uint8(0); // Auras? @@ -20472,7 +20633,8 @@ void Player::CharmSpellInitialize() CharmInfo* charmInfo = charm->GetCharmInfo(); if (!charmInfo) { - TC_LOG_ERROR("entities.player", "Player::CharmSpellInitialize(): the player's charm (%s) has no charminfo!", charm->GetGUID().ToString().c_str()); + TC_LOG_ERROR("entities.player", "Player::CharmSpellInitialize(): Player '%s' (%s) has a charm (%s) but no no charminfo!", + GetName().c_str(), GetGUID().ToString().c_str(), charm->GetGUID().ToString().c_str()); return; } @@ -20517,14 +20679,14 @@ void Player::CharmSpellInitialize() GetSession()->SendPacket(&data); } -void Player::SendRemoveControlBar() +void Player::SendRemoveControlBar() const { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); GetSession()->SendPacket(&data); } -bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell) +bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell) const { if (!mod || !spellInfo) return false; @@ -20542,7 +20704,7 @@ bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod void Player::AddSpellMod(SpellModifier* mod, bool apply) { - TC_LOG_DEBUG("spells", "Player::AddSpellMod %d", mod->spellId); + TC_LOG_DEBUG("spells", "Player::AddSpellMod: Player '%s' (%s), SpellID: %d", GetName().c_str(), GetGUID().ToString().c_str(), mod->spellId); uint16 Opcode = (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER; int i = 0; @@ -20713,7 +20875,7 @@ void Player::SetSpellModTakingSpell(Spell* spell, bool apply) } // send Proficiency -void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) +void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const { WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4); data << uint8(itemClass) << uint32(itemSubclassMask); @@ -20835,13 +20997,13 @@ void Player::SetRestBonus(float rest_bonus_new) // update data for client if ((GetsRecruitAFriendBonus(true) && (GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0))) - SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RAF_LINKED); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_RAF_LINKED); else { if (m_rest_bonus > 10) - SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RESTED); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_RESTED); else if (m_rest_bonus <= 1) - SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_NOT_RAF_LINKED); + SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_NOT_RAF_LINKED); } //RestTickUpdate @@ -20860,7 +21022,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc return false; } - if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) + if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL)) return false; // taximaster case @@ -20959,7 +21121,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc uint32 firstcost = 0; uint32 prevnode = sourcenode; - uint32 lastnode = 0; + uint32 lastnode; for (uint32 i = 1; i < nodes.size(); ++i) { @@ -20992,7 +21154,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes // change but I couldn't find a suitable alternative. OK to use class because only DK // can use this taxi. - uint32 mount_display_id = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT)); + uint32 mount_display_id = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == nullptr || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT)); // in spell case allow 0 model if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0) @@ -21052,24 +21214,24 @@ bool Player::ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid /*= 0*/) nodes[0] = entry->from; nodes[1] = entry->to; - return ActivateTaxiPathTo(nodes, NULL, spellid); + return ActivateTaxiPathTo(nodes, nullptr, spellid); } void Player::CleanupAfterTaxiFlight() { m_taxi.ClearTaxiDestinations(); // not destinations, clear source node Dismount(); - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_TAXI_FLIGHT); getHostileRefManager().setOnlineOfflineState(true); } -void Player::ContinueTaxiFlight() +void Player::ContinueTaxiFlight() const { uint32 sourceNode = m_taxi.GetTaxiSource(); if (!sourceNode) return; - TC_LOG_DEBUG("entities.unit", "WORLD: Restart character %u taxi flight", GetGUID().GetCounter()); + TC_LOG_DEBUG("entities.unit", "Player::ContinueTaxiFlight: Restart %s taxi flight", GetGUID().ToString().c_str()); uint32 mountDisplayId = sObjectMgr->GetTaxiMountDisplayId(sourceNode, GetTeam(), true); if (!mountDisplayId) @@ -21082,7 +21244,7 @@ void Player::ContinueTaxiFlight() TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path]; - float distPrev = MAP_SIZE*MAP_SIZE; + float distPrev; float distNext = (nodeList[0]->LocX - GetPositionX())*(nodeList[0]->LocX - GetPositionX()) + (nodeList[0]->LocY - GetPositionY())*(nodeList[0]->LocY - GetPositionY()) + @@ -21171,11 +21333,11 @@ void Player::InitDisplayIds() PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass()); if (!info) { - TC_LOG_ERROR("entities.player", "Player %s (%s) has incorrect race/class pair. Can't init display ids.", GetName().c_str(), GetGUID().ToString().c_str()); + TC_LOG_ERROR("entities.player", "Player::InitDisplayIds: Player '%s' (%s) has incorrect race/class pair. Can't init display ids.", GetName().c_str(), GetGUID().ToString().c_str()); return; } - uint8 gender = GetByteValue(PLAYER_BYTES_3, 0); + uint8 gender = GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER); switch (gender) { case GENDER_FEMALE: @@ -21187,7 +21349,7 @@ void Player::InitDisplayIds() SetNativeDisplayId(info->displayId_m); break; default: - TC_LOG_ERROR("entities.player", "Player %s (%s) has invalid gender %u", GetName().c_str(), GetGUID().ToString().c_str(), gender); + TC_LOG_ERROR("entities.player", "Player::InitDisplayIds: Player '%s' (%s) has invalid gender %u", GetName().c_str(), GetGUID().ToString().c_str(), gender); } } @@ -21200,7 +21362,7 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c CanEquipNewItem(slot, uiDest, item, false); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, NULL, NULL, item); + SendEquipError(msg, nullptr, nullptr, item); return false; } @@ -21270,13 +21432,13 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item); if (!pProto) { - SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0); + SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, item, 0); return false; } if (!(pProto->AllowableClass & getClassMask()) && pProto->Bonding == BIND_WHEN_PICKED_UP && !IsGameMaster()) { - SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0); + SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, item, 0); return false; } @@ -21286,14 +21448,16 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin Creature* creature = GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR); if (!creature) { - TC_LOG_DEBUG("network", "WORLD: BuyItemFromVendor - %s not found or you can't interact with him.", vendorguid.ToString().c_str()); - SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0); + TC_LOG_DEBUG("network", "Player::BuyItemFromVendorSlot: Vendor (%s) not found or player '%s' (%s) can't interact with him.", + vendorguid.ToString().c_str(), GetName().c_str(), GetGUID().ToString().c_str()); + SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, nullptr, item, 0); return false; } if (!sConditionMgr->IsObjectMeetingVendorItemConditions(creature->GetEntry(), item, this, creature)) { - TC_LOG_DEBUG("condition", "BuyItemFromVendor: conditions not met for creature entry %u item %u", creature->GetEntry(), item); + TC_LOG_DEBUG("condition", "Player::BuyItemFromVendorSlot: Player '%s' (%s) doesn't meed conditions for creature (Entry: %u, Item: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), creature->GetEntry(), item); SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0); return false; } @@ -21340,21 +21504,21 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost); if (!iece) { - TC_LOG_ERROR("entities.player", "Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost); + TC_LOG_ERROR("entities.player", "Player::BuyItemFromVendorSlot: Item %u has wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost); return false; } // honor points price if (GetHonorPoints() < (iece->reqhonorpoints * count)) { - SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL); + SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, nullptr, nullptr); return false; } // arena points price if (GetArenaPoints() < (iece->reqarenapoints * count)) { - SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL); + SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, nullptr, nullptr); return false; } @@ -21363,7 +21527,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin { if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count))) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); return false; } } @@ -21372,7 +21536,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating) { // probably not the proper equip err - SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL); + SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, nullptr, nullptr); return false; } } @@ -21383,7 +21547,8 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin uint32 maxCount = MAX_MONEY_AMOUNT / pProto->BuyPrice; if ((uint32)count > maxCount) { - TC_LOG_ERROR("entities.player", "Player %s tried to buy %u item id %u, causing overflow", GetName().c_str(), (uint32)count, pProto->ItemId); + TC_LOG_ERROR("entities.player", "Player::BuyItemFromVendorSlot: Player '%s' (%s) tried to buy item (ItemID: %u, Count: %u), causing overflow", + GetName().c_str(), GetGUID().ToString().c_str(), pProto->ItemId, (uint32)count); count = (uint8)maxCount; } price = pProto->BuyPrice * count; //it should not exceed MAX_MONEY_AMOUNT @@ -21407,7 +21572,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin { if (pProto->BuyCount * count != 1) { - SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL); + SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, nullptr, nullptr); return false; } if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false)) @@ -21415,7 +21580,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin } else { - SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); + SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return false; } @@ -21477,7 +21642,8 @@ void Player::UpdateHomebindTime(uint32 time) data << uint32(m_HomebindTimer); data << uint32(1); GetSession()->SendPacket(&data); - TC_LOG_DEBUG("maps", "PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName().c_str(), GetGUID().GetCounter()); + TC_LOG_DEBUG("maps", "Player::UpdateHomebindTime: Player '%s' (%s) will be teleported to homebind in 60 seconds", + GetName().c_str(), GetGUID().ToString().c_str()); } } @@ -21513,7 +21679,7 @@ void Player::UpdatePvPState(bool onlyFFA) else // in friendly area { if (IsPvP() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && !pvpInfo.EndTimer) - pvpInfo.EndTimer = time(NULL); // start toggle-off + pvpInfo.EndTimer = time(nullptr); // start toggle-off } } @@ -21533,7 +21699,7 @@ void Player::UpdatePvP(bool state, bool _override) } else { - pvpInfo.EndTimer = time(NULL); + pvpInfo.EndTimer = time(nullptr); SetPvP(state); } } @@ -21547,7 +21713,7 @@ void Player::UpdatePotionCooldown(Spell* spell) // Call not from spell cast, send cooldown event for item spells if no in combat if (!spell) { - // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions) + // spell/item pair let set proper cooldown (except non-existing charged spell cooldown spellmods for potions) if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(m_lastPotionId)) for (uint8 idx = 0; idx < MAX_ITEM_PROTO_SPELLS; ++idx) if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE) @@ -21561,26 +21727,19 @@ void Player::UpdatePotionCooldown(Spell* spell) m_lastPotionId = 0; } -void Player::setResurrectRequestData(ObjectGuid guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana) +void Player::SetResurrectRequestData(Unit* caster, uint32 health, uint32 mana, uint32 appliedAura) { - m_resurrectGUID = guid; - m_resurrectMap = mapId; - m_resurrectX = X; - m_resurrectY = Y; - m_resurrectZ = Z; - m_resurrectHealth = health; - m_resurrectMana = mana; + ASSERT(!IsResurrectRequested()); + _resurrectionData.reset(new ResurrectionData()); + _resurrectionData->GUID = caster->GetGUID(); + _resurrectionData->Location.WorldRelocate(*caster); + _resurrectionData->Health = health; + _resurrectionData->Mana = mana; + _resurrectionData->Aura = appliedAura; } -void Player::clearResurrectRequestData() -{ - setResurrectRequestData(ObjectGuid::Empty, 0, 0.0f, 0.0f, 0.0f, 0, 0); - - m_ghoulResurrectPlayerGUID = ObjectGuid::Empty; - m_ghoulResurrectGhoulGUID = ObjectGuid::Empty; -} //slot to be excluded while counting -bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) +bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) const { if (!enchantmentcondition) return true; @@ -21659,7 +21818,8 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) } } - TC_LOG_DEBUG("entities.player.items", "Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no"); + TC_LOG_DEBUG("entities.player.items", "Player::EnchantmentFitsRequirements: Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", + enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no"); return activate; } @@ -21771,7 +21931,7 @@ void Player::SetBattlegroundEntryPoint() if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam())) m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f); else - TC_LOG_ERROR("entities.player", "SetBattlegroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId()); + TC_LOG_ERROR("entities.player", "Player::SetBattlegroundEntryPoint: Dungeon (MapID: %u) has no linked graveyard, setting home location as entry point.", GetMapId()); } // If new entry point is not BG or arena set it else if (!GetMap()->IsBattlegroundOrArena()) @@ -21785,7 +21945,7 @@ void Player::SetBattlegroundEntryPoint() void Player::SetBGTeam(uint32 team) { m_bgData.bgTeam = team; - SetByteValue(PLAYER_BYTES_3, 3, uint8(team == ALLIANCE ? 1 : 0)); + SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_ARENA_FACTION, uint8(team == ALLIANCE ? 1 : 0)); } uint32 Player::GetBGTeam() const @@ -21866,8 +22026,8 @@ void Player::ReportedAfkBy(Player* reporter) if (m_bgData.bgAfkReporter.find(reporter->GetGUID().GetCounter()) == m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit()) { m_bgData.bgAfkReporter.insert(reporter->GetGUID().GetCounter()); - // 3 players have to complain to apply debuff - if (m_bgData.bgAfkReporter.size() >= 3) + // by default 3 players have to complain to apply debuff + if (m_bgData.bgAfkReporter.size() >= sWorld->getIntConfig(CONFIG_BATTLEGROUND_REPORT_AFK)) { // cast 'Idle' spell CastSpell(this, 43680, true); @@ -21885,7 +22045,7 @@ WorldLocation Player::GetStartPosition() const return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0); } -bool Player::HaveAtClient(WorldObject const* u) const +bool Player::HaveAtClient(Object const* u) const { return u == this || m_clientGUIDs.find(u->GetGUID()) != m_clientGUIDs.end(); } @@ -21982,7 +22142,7 @@ template<> inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p) { if (p->GetPetGUID() == t->GetGUID() && t->IsPet()) - ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true); + t->ToPet()->Remove(PET_SAVE_NOT_IN_SLOT, true); } void Player::UpdateVisibilityOf(WorldObject* target) @@ -22016,7 +22176,7 @@ void Player::UpdateVisibilityOf(WorldObject* target) // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if (target->isType(TYPEMASK_UNIT)) - SendInitialVisiblePackets((Unit*)target); + SendInitialVisiblePackets(static_cast<Unit*>(target)); } } } @@ -22063,7 +22223,7 @@ void Player::UpdateTriggerVisibility() GetSession()->SendPacket(&packet); } -void Player::SendInitialVisiblePackets(Unit* target) +void Player::SendInitialVisiblePackets(Unit* target) const { SendAurasForTarget(target); if (target->IsAlive()) @@ -22152,7 +22312,7 @@ bool Player::ModifyMoney(int32 amount, bool sendError /*= true*/) sScriptMgr->OnPlayerMoneyLimit(this, amount); if (sendError) - SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL); + SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, nullptr, nullptr); return false; } } @@ -22183,14 +22343,14 @@ Unit* Player::GetSelectedUnit() const { if (ObjectGuid selectionGUID = GetTarget()) return ObjectAccessor::GetUnit(*this, selectionGUID); - return NULL; + return nullptr; } Player* Player::GetSelectedPlayer() const { if (ObjectGuid selectionGUID = GetTarget()) return ObjectAccessor::GetPlayer(*this, selectionGUID); - return NULL; + return nullptr; } void Player::SendComboPoints() @@ -22281,7 +22441,7 @@ void Player::ClearComboPoints() void Player::SetGroup(Group* group, int8 subgroup) { - if (group == NULL) + if (group == nullptr) m_group.unlink(); else { @@ -22421,7 +22581,7 @@ void Player::SendUpdateToOutOfRangeGroupMembers() pet->ResetAuraUpdateMaskForRaid(); } -void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg) +void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg) const { WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2); data << uint32(mapid); @@ -22440,7 +22600,7 @@ void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 GetSession()->SendPacket(&data); } -void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) +void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const { // type of warning, based on the time remaining until reset uint32 type; @@ -22486,7 +22646,7 @@ void Player::ApplyEquipCooldown(Item* pItem) continue; // Don't replace longer cooldowns by equip cooldown if we have any. - if (GetSpellHistory()->GetRemainingCooldown(sSpellMgr->EnsureSpellInfo(spellData.SpellId)) > 30 * IN_MILLISECONDS) + if (GetSpellHistory()->GetRemainingCooldown(sSpellMgr->AssertSpellInfo(spellData.SpellId)) > 30 * IN_MILLISECONDS) continue; GetSpellHistory()->AddCooldown(spellData.SpellId, pItem->GetEntry(), std::chrono::seconds(30)); @@ -22564,7 +22724,8 @@ void Player::LearnCustomSpells() for (PlayerCreateInfoSpells::const_iterator itr = info->customSpells.begin(); itr != info->customSpells.end(); ++itr) { uint32 tspell = *itr; - TC_LOG_DEBUG("entities.player.loading", "PLAYER (Class: %u Race: %u): Adding initial spell, id = %u", uint32(getClass()), uint32(getRace()), tspell); + TC_LOG_DEBUG("entities.player.loading", "Player::LearnCustomSpells: Player '%s' (%s, Class: %u Race: %u): Adding initial spell (SpellID: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), uint32(getClass()), uint32(getRace()), tspell); if (!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add AddSpell(tspell, true, true, true, false); else // but send in normal spell in game learn case @@ -22736,7 +22897,7 @@ void Player::LearnSkillRewardedSpells(uint32 skillId, uint32 skillValue) } } -void Player::SendAurasForTarget(Unit* target) +void Player::SendAurasForTarget(Unit* target) const { if (!target || target->GetVisibleAuras()->empty()) // speedup things return; @@ -22777,7 +22938,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(NULL); // last daily quest time + m_lastDailyQuestTime = time(nullptr); // last daily quest time m_DailyQuestChanged = true; break; } @@ -22785,12 +22946,30 @@ void Player::SetDailyQuestStatus(uint32 quest_id) } else { m_DFQuests.insert(quest_id); - m_lastDailyQuestTime = time(NULL); + m_lastDailyQuestTime = time(nullptr); m_DailyQuestChanged = true; } } } +bool Player::IsDailyQuestDone(uint32 quest_id) +{ + bool found = false; + if (sObjectMgr->GetQuestTemplate(quest_id)) + { + for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) + { + if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx) == quest_id) + { + found = true; + break; + } + } + } + + return found; +} + void Player::SetWeeklyQuestStatus(uint32 quest_id) { m_weeklyquests.insert(quest_id); @@ -22858,7 +23037,7 @@ void Player::ResetMonthlyQuestStatus() Battleground* Player::GetBattleground() const { if (GetBattlegroundId() == 0) - return NULL; + return nullptr; return sBattlegroundMgr->GetBattleground(GetBattlegroundId(), m_bgData.bgTypeID); } @@ -22917,7 +23096,7 @@ uint32 Player::AddBattlegroundQueueId(BattlegroundQueueTypeId val) return PLAYER_MAX_BATTLEGROUND_QUEUES; } -bool Player::HasFreeBattlegroundQueueId() +bool Player::HasFreeBattlegroundQueueId() const { for (uint8 i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattlegroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE) @@ -23103,13 +23282,32 @@ void Player::UpdateForQuestWorldObjects() GetSession()->SendPacket(&packet); } -void Player::SetSummonPoint(uint32 mapid, float x, float y, float z) +bool Player::HasSummonPending() const { - m_summon_expire = time(NULL) + MAX_PLAYER_SUMMON_DELAY; - m_summon_mapid = mapid; - m_summon_x = x; - m_summon_y = y; - m_summon_z = z; + return m_summon_expire >= time(nullptr); +} + +void Player::SendSummonRequestFrom(Unit* summoner) +{ + if (!summoner) + return; + + // Player already has active summon request + if (HasSummonPending()) + return; + + // Evil Twin (ignore player summon, but hide this for summoner) + if (HasAura(23445)) + return; + + m_summon_expire = time(nullptr) + MAX_PLAYER_SUMMON_DELAY; + m_summon_location.WorldRelocate(*summoner); + + WorldPacket data(SMSG_SUMMON_REQUEST, 8 + 4 + 4); + data << uint64(summoner->GetGUID()); // summoner guid + data << uint32(summoner->GetZoneId()); // summoner zone + data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs + GetSession()->SendPacket(&data); } void Player::SummonIfPossible(bool agree) @@ -23121,7 +23319,7 @@ void Player::SummonIfPossible(bool agree) } // expire and auto declined - if (m_summon_expire < time(NULL)) + if (m_summon_expire < time(nullptr)) return; // stop taxi flight at summon @@ -23140,7 +23338,7 @@ void Player::SummonIfPossible(bool agree) UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1); - TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z, GetOrientation()); + TeleportTo(m_summon_location); } void Player::RemoveItemDurations(Item* item) @@ -23179,8 +23377,7 @@ void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/) return; ItemPosCountVec off_dest; - uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false); - if (off_msg == EQUIP_ERR_OK) + if (CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) == EQUIP_ERR_OK) { RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true); StoreItem(off_dest, offItem, true); @@ -23242,7 +23439,7 @@ bool Player::HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item cons break; } default: - TC_LOG_ERROR("entities.player", "HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", spellInfo->EquippedItemClass); + TC_LOG_ERROR("entities.player", "Player::HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", spellInfo->EquippedItemClass); break; } @@ -23368,7 +23565,7 @@ bool Player::GetsRecruitAFriendBonus(bool forXP) { if (Group* group = this->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player) @@ -23417,7 +23614,7 @@ void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewar // prepare data for near group iteration if (Group* group = GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player) @@ -23483,8 +23680,14 @@ void Player::ResurrectUsingRequestData() { RemoveGhoul(); + if (uint32 aura = _resurrectionData->Aura) + { + CastSpell(this, aura, true, nullptr, nullptr, _resurrectionData->GUID); + return; + } + /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse - TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation()); + TeleportTo(_resurrectionData->Location); if (IsBeingTeleported()) { @@ -23492,15 +23695,20 @@ void Player::ResurrectUsingRequestData() return; } + ResurrectUsingRequestDataImpl(); +} + +void Player::ResurrectUsingRequestDataImpl() +{ ResurrectPlayer(0.0f, false); - if (GetMaxHealth() > m_resurrectHealth) - SetHealth(m_resurrectHealth); + if (GetMaxHealth() > _resurrectionData->Health) + SetHealth(_resurrectionData->Health); else SetFullHealth(); - if (GetMaxPower(POWER_MANA) > m_resurrectMana) - SetPower(POWER_MANA, m_resurrectMana); + if (GetMaxPower(POWER_MANA) > _resurrectionData->Mana) + SetPower(POWER_MANA, _resurrectionData->Mana); else SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); @@ -23527,7 +23735,7 @@ void Player::SetClientControl(Unit* target, bool allowMove) void Player::SetMover(Unit* target) { - m_mover->m_movedPlayer = NULL; + m_mover->m_movedPlayer = nullptr; m_mover = target; m_mover->m_movedPlayer = this; } @@ -23572,7 +23780,7 @@ uint32 Player::GetCorpseReclaimDelay(bool pvp) const else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)) return 0; - time_t now = time(NULL); + time_t now = time(nullptr); // 0..2 full period // should be ceil(x)-1 but not floor(x) uint64 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now) / DEATH_EXPIRE_STEP : 0; @@ -23587,7 +23795,7 @@ void Player::UpdateCorpseReclaimDelay() (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))) return; - time_t now = time(NULL); + time_t now = time(nullptr); if (now < m_deathExpireTime) { @@ -23603,7 +23811,7 @@ void Player::UpdateCorpseReclaimDelay() m_deathExpireTime = now + DEATH_EXPIRE_STEP; } -int32 Player::CalculateCorpseReclaimDelay(bool load) +int32 Player::CalculateCorpseReclaimDelay(bool load) const { Corpse* corpse = GetCorpse(); @@ -23631,7 +23839,7 @@ int32 Player::CalculateCorpseReclaimDelay(bool load) } time_t expected_time = corpse->GetGhostTime() + copseReclaimDelay[count]; - time_t now = time(NULL); + time_t now = time(nullptr); if (now >= expected_time) return -1; @@ -23644,7 +23852,7 @@ int32 Player::CalculateCorpseReclaimDelay(bool load) return delay * IN_MILLISECONDS; } -void Player::SendCorpseReclaimDelay(uint32 delay) +void Player::SendCorpseReclaimDelay(uint32 delay) const { WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); data << uint32(delay); @@ -23655,12 +23863,12 @@ Player* Player::GetNextRandomRaidMember(float radius) { Group* group = GetGroup(); if (!group) - return NULL; + return nullptr; std::vector<Player*> nearMembers; nearMembers.reserve(group->GetMembersCount()); - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* Target = itr->GetSource(); @@ -23671,7 +23879,7 @@ Player* Player::GetNextRandomRaidMember(float radius) } if (nearMembers.empty()) - return NULL; + return nullptr; uint32 randTarget = urand(0, nearMembers.size()-1); return nearMembers[randTarget]; @@ -23703,7 +23911,7 @@ PartyResult Player::CanUninviteFromGroup(ObjectGuid guidMember) const return ERR_PARTY_LFG_BOOT_LOOT_ROLLS; /// @todo Should also be sent when anyone has recently left combat, with an aprox ~5 seconds timer. - for (GroupReference const* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference const* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) if (itr->GetSource() && itr->GetSource()->IsInCombat()) return ERR_PARTY_LFG_BOOT_IN_COMBAT; @@ -23727,12 +23935,12 @@ PartyResult Player::CanUninviteFromGroup(ObjectGuid guidMember) const return ERR_PARTY_RESULT_OK; } -bool Player::isUsingLfg() +bool Player::isUsingLfg() const { return sLFGMgr->GetState(GetGUID()) != lfg::LFG_STATE_NONE; } -bool Player::inRandomLfgDungeon() +bool Player::inRandomLfgDungeon() const { if (sLFGMgr->selectedRandomLfgDungeon(GetGUID())) { @@ -23762,12 +23970,12 @@ void Player::RemoveFromBattlegroundOrBattlefieldRaid() m_group.link(group, this); m_group.setSubGroup(GetOriginalSubGroup()); } - SetOriginalGroup(NULL); + SetOriginalGroup(nullptr); } void Player::SetOriginalGroup(Group* group, int8 subgroup) { - if (group == NULL) + if (group == nullptr) m_originalGroup.unlink(); else { @@ -23788,7 +23996,7 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) if (_lastLiquid && _lastLiquid->SpellId) RemoveAurasDueToSpell(_lastLiquid->SpellId); - _lastLiquid = NULL; + _lastLiquid = nullptr; return; } @@ -23814,7 +24022,7 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) else if (_lastLiquid && _lastLiquid->SpellId) { RemoveAurasDueToSpell(_lastLiquid->SpellId); - _lastLiquid = NULL; + _lastLiquid = nullptr; } @@ -23869,7 +24077,7 @@ void Player::SetCanBlock(bool value) UpdateBlockPercentage(); } -bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const +bool ItemPosCount::isContainedIn(std::vector<ItemPosCount> const& vec) const { for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr) if (itr->pos == pos) @@ -23877,15 +24085,15 @@ bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const return false; } -void Player::StopCastingBindSight() +void Player::StopCastingBindSight() const { if (WorldObject* target = GetViewpoint()) { if (target->isType(TYPEMASK_UNIT)) { - ((Unit*)target)->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID()); - ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID()); - ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID()); + static_cast<Unit*>(target)->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID()); + static_cast<Unit*>(target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID()); + static_cast<Unit*>(target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID()); } } } @@ -23894,11 +24102,12 @@ void Player::SetViewpoint(WorldObject* target, bool apply) { if (apply) { - TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName().c_str(), target->GetEntry(), target->GetTypeId()); + TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player '%s' (%s) creates seer (Entry: %u, TypeId: %u).", + GetName().c_str(), GetGUID().ToString().c_str(), target->GetEntry(), target->GetTypeId()); if (!AddGuidValue(PLAYER_FARSIGHT, target->GetGUID())) { - TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName().c_str()); + TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player '%s' (%s) cannot add new viewpoint!", GetName().c_str(), GetGUID().ToString().c_str()); return; } @@ -23906,23 +24115,24 @@ void Player::SetViewpoint(WorldObject* target, bool apply) UpdateVisibilityOf(target); if (target->isType(TYPEMASK_UNIT) && target != GetVehicleBase()) - ((Unit*)target)->AddPlayerToVision(this); + static_cast<Unit*>(target)->AddPlayerToVision(this); + SetSeer(target); } else { - TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player %s remove seer", GetName().c_str()); + TC_LOG_DEBUG("maps", "Player::CreateViewpoint: Player %s removed seer", GetName().c_str()); if (!RemoveGuidValue(PLAYER_FARSIGHT, target->GetGUID())) { - TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName().c_str()); + TC_LOG_FATAL("entities.player", "Player::CreateViewpoint: Player '%s' (%s) cannot remove current viewpoint!", GetName().c_str(), GetGUID().ToString().c_str()); return; } if (target->isType(TYPEMASK_UNIT) && target != GetVehicleBase()) - ((Unit*)target)->RemovePlayerFromVision(this); + static_cast<Unit*>(target)->RemovePlayerFromVision(this); //must immediately set seer back otherwise may crash - m_seer = this; + SetSeer(this); //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0); //GetSession()->SendPacket(&data); @@ -23957,11 +24167,11 @@ void Player::SetViewpoint(WorldObject* target, bool apply) WorldObject* Player::GetViewpoint() const { if (ObjectGuid guid = GetGuidValue(PLAYER_FARSIGHT)) - return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER); - return NULL; + return static_cast<WorldObject*>(ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER)); + return nullptr; } -bool Player::CanUseBattlegroundObject(GameObject* gameobject) +bool Player::CanUseBattlegroundObject(GameObject* gameobject) const { // It is possible to call this method with a null pointer, only skipping faction check. if (gameobject) @@ -23980,24 +24190,24 @@ bool Player::CanUseBattlegroundObject(GameObject* gameobject) IsAlive()); // Alive } -bool Player::CanCaptureTowerPoint() +bool Player::CanCaptureTowerPoint() const { return (!HasStealthAura() && // not stealthed !HasInvisibilityAura() && // not invisible IsAlive()); // live player } -uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin) +uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin) const { uint8 level = getLevel(); if (level > GT_MAX_LEVEL) level = GT_MAX_LEVEL; // max level in this dbc - uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2); - uint8 haircolor = GetByteValue(PLAYER_BYTES, 3); - uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0); - uint8 skincolor = GetByteValue(PLAYER_BYTES, 0); + uint8 hairstyle = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID); + uint8 haircolor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID); + uint8 facialhair = GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE); + uint8 skincolor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID); if ((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->hair_id == skincolor))) return 0; @@ -24055,7 +24265,7 @@ void Player::SetGlyph(uint8 slot, uint32 glyph) SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph); } -bool Player::isTotalImmune() +bool Player::isTotalImmune() const { AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY); @@ -24105,7 +24315,7 @@ void Player::SetTitle(CharTitlesEntry const* title, bool lost) GetSession()->SendPacket(&data); } -bool Player::isTotalImmunity() +bool Player::isTotalImmunity() const { AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY); @@ -24129,38 +24339,6 @@ bool Player::isTotalImmunity() return false; } -void Player::UpdateCharmedAI() -{ - //This should only called in Player::Update - Creature* charmer = GetCharmer()->ToCreature(); - - //kill self if charm aura has infinite duration - if (charmer->IsInEvadeMode()) - { - AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); - for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) - if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) - { - charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); - return; - } - } - - if (!charmer->IsInCombat()) - GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); - - Unit* target = GetVictim(); - if (!target || !charmer->IsValidAttackTarget(target)) - { - target = charmer->SelectNearestTarget(); - if (!target) - return; - - GetMotionMaster()->MoveChase(target); - Attack(target, true); - } -} - uint32 Player::GetRuneBaseCooldown(uint8 index) { uint8 rune = GetBaseRune(index); @@ -24213,7 +24391,7 @@ void Player::RemoveRunesByAuraEffect(AuraEffect const* aura) if (m_runes->runes[i].ConvertAura == aura) { ConvertRune(i, GetBaseRune(i)); - SetRuneConvertAura(i, NULL); + SetRuneConvertAura(i, nullptr); } } } @@ -24221,11 +24399,11 @@ void Player::RemoveRunesByAuraEffect(AuraEffect const* aura) void Player::RestoreBaseRune(uint8 index) { AuraEffect const* aura = m_runes->runes[index].ConvertAura; - // If rune was converted by a non-pasive aura that still active we should keep it converted + // If rune was converted by a non-passive aura that still active we should keep it converted if (aura && !aura->GetSpellInfo()->HasAttribute(SPELL_ATTR0_PASSIVE)) return; ConvertRune(index, GetBaseRune(index)); - SetRuneConvertAura(index, NULL); + SetRuneConvertAura(index, nullptr); // Don't drop passive talents providing rune convertion if (!aura || aura->GetAuraType() != SPELL_AURA_CONVERT_RUNE) return; @@ -24247,7 +24425,7 @@ void Player::ConvertRune(uint8 index, RuneType newType) GetSession()->SendPacket(&data); } -void Player::ResyncRunes(uint8 count) +void Player::ResyncRunes(uint8 count) const { WorldPacket data(SMSG_RESYNC_RUNES, 4 + count * 2); data << uint32(count); @@ -24259,7 +24437,7 @@ void Player::ResyncRunes(uint8 count) GetSession()->SendPacket(&data); } -void Player::AddRunePower(uint8 index) +void Player::AddRunePower(uint8 index) const { WorldPacket data(SMSG_ADD_RUNE_POWER, 4); data << uint32(1 << index); // mask (0x00-0x3F probably) @@ -24293,7 +24471,7 @@ void Player::InitRunes() SetRuneCooldown(i, 0); // reset cooldowns SetRuneTimer(i, 0xFFFFFFFF); // Reset rune flags SetLastRuneGraceTimer(i, 0); - SetRuneConvertAura(i, NULL); + SetRuneConvertAura(i, nullptr); m_runes->SetRuneState(i); } @@ -24328,7 +24506,7 @@ void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore cons msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, lootItem->itemid, lootItem->count); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, NULL, NULL, lootItem->itemid); + SendEquipError(msg, nullptr, nullptr, lootItem->itemid); continue; } @@ -24339,15 +24517,15 @@ void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore cons void Player::StoreLootItem(uint8 lootSlot, Loot* loot) { - QuestItem* qitem = NULL; - QuestItem* ffaitem = NULL; - QuestItem* conditem = NULL; + QuestItem* qitem = nullptr; + QuestItem* ffaitem = nullptr; + QuestItem* conditem = nullptr; LootItem* item = loot->LootItemInSlot(lootSlot, this, &qitem, &ffaitem, &conditem); if (!item) { - SendEquipError(EQUIP_ERR_ALREADY_LOOTED, NULL, NULL); + SendEquipError(EQUIP_ERR_ALREADY_LOOTED, nullptr, nullptr); return; } @@ -24414,7 +24592,7 @@ void Player::StoreLootItem(uint8 lootSlot, Loot* loot) } else - SendEquipError(msg, NULL, NULL, item->itemid); + SendEquipError(msg, nullptr, nullptr, item->itemid); } uint32 Player::CalculateTalentsPoints() const @@ -24467,8 +24645,8 @@ void Player::_LoadSkills(PreparedQueryResult result) SkillRaceClassInfoEntry const* rcEntry = GetSkillRaceClassInfo(skill, getRace(), getClass()); if (!rcEntry) { - TC_LOG_ERROR("entities.player", "Character: %s (GUID: %u Race: %u Class: %u) has skill %u not allowed for his race/class combination", - GetName().c_str(), GetGUID().GetCounter(), uint32(getRace()), uint32(getClass()), skill); + TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '%s' (%s, Race: %u, Class: %u) has forbidden skill %u for his race/class combination", + GetName().c_str(), GetGUID().ToString().c_str(), uint32(getRace()), uint32(getClass()), skill); mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(0, SKILL_DELETED))); continue; @@ -24491,7 +24669,8 @@ void Player::_LoadSkills(PreparedQueryResult result) if (value == 0) { - TC_LOG_ERROR("entities.player", "Character %u has skill %u with value 0. Will be deleted.", GetGUID().GetCounter(), skill); + TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '%s' (%s) has skill %u with value 0, deleted.", + GetName().c_str(), GetGUID().ToString().c_str(), skill); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL); @@ -24528,7 +24707,8 @@ void Player::_LoadSkills(PreparedQueryResult result) if (count >= PLAYER_MAX_SKILLS) // client limit { - TC_LOG_ERROR("entities.player", "Character %u has more than %u skills.", GetGUID().GetCounter(), PLAYER_MAX_SKILLS); + TC_LOG_ERROR("entities.player", "Player::_LoadSkills: Player '%s' (%s) has more than %u skills.", + GetName().c_str(), GetGUID().ToString().c_str(), PLAYER_MAX_SKILLS); break; } } @@ -24795,30 +24975,13 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) - { - uint32 numRows = sTalentStore.GetNumRows(); - for (uint32 i = 0; i < numRows; i++) // Loop through all talents. - { - // Someday, someone needs to revamp - const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i); - if (tmpTalent) // the way talents are tracked - { + for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++) // Loop through all talents. + if (const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i)) // the way talents are tracked if (tmpTalent->TalentTab == tTab) - { for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++) - { if (tmpTalent->RankID[rank] != 0) - { if (HasSpell(tmpTalent->RankID[rank])) - { spentPoints += (rank + 1); - } - } - } - } - } - } - } // not have required min points spent in talent tree if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK)) @@ -24828,7 +24991,7 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) uint32 spellid = talentInfo->RankID[talentRank]; if (spellid == 0) { - TC_LOG_ERROR("entities.player", "Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); + TC_LOG_ERROR("entities.player", "Player::LearnTalent: Talent.dbc has no spellInfo for talent: %u (spell id = 0)", talentId); return; } @@ -24840,7 +25003,7 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) LearnSpell(spellid, false); AddTalent(spellid, m_activeSpec, true); - TC_LOG_DEBUG("entities.player", "TalentID: %u Rank: %u Spell: %u Spec: %u\n", talentId, talentRank, spellid, m_activeSpec); + TC_LOG_DEBUG("misc", "Player::LearnTalent: TalentID: %u Spell: %u Group: %u\n", talentId, spellid, uint32(m_activeSpec)); // update free talent points SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1)); @@ -24965,7 +25128,7 @@ void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRa uint32 spellid = talentInfo->RankID[talentRank]; if (spellid == 0) { - TC_LOG_ERROR("entities.player", "Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank); + TC_LOG_ERROR("entities.player", "Talent.dbc contains talent: %u Rank: %u spell id = 0", talentId, talentRank); return; } @@ -25292,7 +25455,8 @@ void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) if (!found) // something wrong... { - TC_LOG_ERROR("entities.player", "Player %s tried to save equipment set " UI64FMTD " (index %u), but that equipment set not found!", GetName().c_str(), eqset.Guid, index); + TC_LOG_ERROR("entities.player", "Player::SetEquipmentSet: Player '%s' (%s) tried to save nonexistent equipment set " UI64FMTD " (index: %u)", + GetName().c_str(), GetGUID().ToString().c_str(), eqset.Guid, index); return; } } @@ -25322,7 +25486,7 @@ void Player::_SaveEquipmentSets(SQLTransaction& trans) { uint32 index = itr->first; EquipmentSet& eqset = itr->second; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; uint8 j = 0; switch (eqset.state) { @@ -25460,7 +25624,7 @@ void Player::_LoadGlyphs(PreparedQueryResult result) while (result->NextRow()); } -void Player::_SaveGlyphs(SQLTransaction& trans) +void Player::_SaveGlyphs(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS); stmt->setUInt32(0, GetGUID().GetCounter()); @@ -25544,7 +25708,7 @@ void Player::UpdateSpecCount(uint8 count) ActivateSpec(0); SQLTransaction trans = CharacterDatabase.BeginTransaction(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt; // Copy spec data if (count > curCount) @@ -25635,7 +25799,7 @@ void Player::ActivateSpec(uint8 spec) for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) { - // skip non-existant talent ranks + // skip non-existing talent ranks if (talentInfo->RankID[rank] == 0) continue; RemoveSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells.. @@ -25679,7 +25843,7 @@ void Player::ActivateSpec(uint8 spec) // learn highest talent rank that exists in newly activated spec for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) { - // skip non-existant talent ranks + // skip non-existing talent ranks if (talentInfo->RankID[rank] == 0) continue; // if the talent can be found in the newly activated PlayerTalentMap @@ -25752,7 +25916,7 @@ uint32 Player::GetReputation(uint32 factionentry) const return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry)); } -std::string const& Player::GetGuildName() +std::string const& Player::GetGuildName() const { return sGuildMgr->GetGuildById(GetGuildId())->GetName(); } @@ -25960,7 +26124,7 @@ void Player::SendItemRetrievalMail(uint32 itemEntry, uint32 count) MailDraft draft("Recovered Item", "We recovered a lost item in the twisting nether and noted that it was yours.$B$BPlease find said object enclosed."); // This is the text used in Cataclysm, it probably wasn't changed. SQLTransaction trans = CharacterDatabase.BeginTransaction(); - if (Item* item = Item::CreateItem(itemEntry, count, 0)) + if (Item* item = Item::CreateItem(itemEntry, count, nullptr)) { item->SaveToDB(trans); draft.AddItem(item); @@ -25991,7 +26155,7 @@ void Player::_LoadRandomBGStatus(PreparedQueryResult result) m_IsBGRandomWinner = true; } -float Player::GetAverageItemLevel() +float Player::GetAverageItemLevel() const { float sum = 0; uint32 count = 0; @@ -26073,6 +26237,9 @@ bool Player::SetCanFly(bool apply, bool packetOnly /*= false*/) if (!packetOnly && !Unit::SetCanFly(apply)) return false; + if (!apply) + SetFallInformation(0, GetPositionZ()); + WorldPacket data(apply ? SMSG_MOVE_SET_CAN_FLY : SMSG_MOVE_UNSET_CAN_FLY, 12); data << GetPackGUID(); data << uint32(0); //! movement counter @@ -26169,7 +26336,7 @@ float Player::GetCollisionHeight(bool mounted) const } } -std::string Player::GetMapAreaAndZoneString() +std::string Player::GetMapAreaAndZoneString() const { uint32 areaId = GetAreaId(); std::string areaName = "Unknown"; @@ -26187,7 +26354,7 @@ std::string Player::GetMapAreaAndZoneString() return str.str(); } -std::string Player::GetCoordsMapAreaAndZoneString() +std::string Player::GetCoordsMapAreaAndZoneString() const { std::ostringstream str; str << Position::ToString() << " " << GetMapAreaAndZoneString(); @@ -26222,38 +26389,38 @@ Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetTy if (duration > 0) pet->SetDuration(duration); - return NULL; + return nullptr; } // petentry == 0 for hunter "call pet" (current pet summoned if any) if (!entry) { delete pet; - return NULL; + return nullptr; } pet->Relocate(x, y, z, ang); if (!pet->IsPositionValid()) { - TC_LOG_ERROR("misc", "Pet (guidlow %d, entry %d) not summoned. Suggested coordinates isn't valid (X: %f Y: %f)", pet->GetGUID().GetCounter(), pet->GetEntry(), pet->GetPositionX(), pet->GetPositionY()); + TC_LOG_ERROR("misc", "Player::SummonPet: Pet (%s, Entry: %d) not summoned. Suggested coordinates aren't valid (X: %f Y: %f)", pet->GetGUID().ToString().c_str(), pet->GetEntry(), pet->GetPositionX(), pet->GetPositionY()); delete pet; - return NULL; + return nullptr; } Map* map = GetMap(); uint32 pet_number = sObjectMgr->GeneratePetNumber(); if (!pet->Create(map->GenerateLowGuid<HighGuid::Pet>(), map, GetPhaseMask(), entry, pet_number)) { - TC_LOG_ERROR("misc", "no such creature entry %u", entry); + TC_LOG_ERROR("misc", "Player::SummonPet: No such creature entry %u", entry); delete pet; - return NULL; + return nullptr; } pet->SetCreatorGUID(GetGUID()); pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction()); pet->setPowerType(POWER_MANA); - pet->SetUInt32Value(UNIT_NPC_FLAGS, 0); + pet->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); pet->SetUInt32Value(UNIT_FIELD_BYTES_1, 0); pet->InitStatsForLevel(getLevel()); @@ -26264,12 +26431,12 @@ Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetTy case SUMMON_PET: // this enables pet details window (Shift+P) pet->GetCharmInfo()->SetPetNumber(pet_number, true); - pet->SetUInt32Value(UNIT_FIELD_BYTES_0, 2048); + pet->SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, CLASS_MAGE); 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(NULL))); // cast can't be helped in this case + pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped in this case break; default: break; @@ -26313,7 +26480,7 @@ Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetTy return pet; } -void Player::SendSupercededSpell(uint32 oldSpell, uint32 newSpell) +void Player::SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const { WorldPacket data(SMSG_SUPERCEDED_SPELL, 8); data << uint32(oldSpell) << uint32(newSpell); @@ -26401,3 +26568,22 @@ void Player::RemoveRestFlag(RestFlag restFlag) RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); } } + +uint32 Player::DoRandomRoll(uint32 minimum, uint32 maximum) +{ + ASSERT(maximum <= 10000); + + uint32 roll = urand(minimum, maximum); + + WorldPacket data(MSG_RANDOM_ROLL, 4 + 4 + 4 + 8); + data << uint32(minimum); + data << uint32(maximum); + data << uint32(roll); + data << GetGUID(); + if (Group* group = GetGroup()) + group->BroadcastPacket(&data, false); + else + SendDirectMessage(&data); + + return roll; +} diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 2388cf9d0c7..38fff9b8d83 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -30,6 +30,7 @@ #include "SpellHistory.h" #include "Unit.h" #include "TradeData.h" +#include "CinematicMgr.h" #include <limits> #include <string> @@ -54,6 +55,7 @@ class PlayerMenu; class PlayerSocial; class SpellCastTargets; class UpdateMask; +class PlayerAI; struct CharacterCustomizeInfo; @@ -116,7 +118,7 @@ struct PlayerTalent // Spell modifier (used for modify other spells) struct SpellModifier { - SpellModifier(Aura* _ownerAura = NULL) : op(SPELLMOD_DAMAGE), type(SPELLMOD_FLAT), charges(0), value(0), mask(), spellId(0), ownerAura(_ownerAura) { } + SpellModifier(Aura* _ownerAura = nullptr) : op(SPELLMOD_DAMAGE), type(SPELLMOD_FLAT), charges(0), value(0), mask(), spellId(0), ownerAura(_ownerAura) { } SpellModOp op : 8; SpellModType type : 8; int16 charges : 16; @@ -255,7 +257,7 @@ typedef std::list<PlayerCreateInfoSkill> PlayerCreateInfoSkills; struct PlayerInfo { // existence checked by displayId != 0 - PlayerInfo() : mapId(0), areaId(0), positionX(0.0f), positionY(0.0f), positionZ(0.0f), orientation(0.0f), displayId_m(0), displayId_f(0), levelInfo(NULL) { } + PlayerInfo() : mapId(0), areaId(0), positionX(0.0f), positionY(0.0f), positionZ(0.0f), orientation(0.0f), displayId_m(0), displayId_f(0), levelInfo(nullptr) { } uint32 mapId; uint32 areaId; @@ -267,6 +269,7 @@ struct PlayerInfo uint16 displayId_f; PlayerCreateInfoItems item; PlayerCreateInfoSpells customSpells; + PlayerCreateInfoSpells castSpells; PlayerCreateInfoActions action; PlayerCreateInfoSkills skills; @@ -286,7 +289,7 @@ struct PvPInfo struct DuelInfo { - DuelInfo() : initiator(NULL), opponent(NULL), startTimer(0), startTime(0), outOfBound(0), isMounted(false) { } + DuelInfo() : initiator(nullptr), opponent(nullptr), startTimer(0), startTime(0), outOfBound(0), isMounted(false), isCompleted(false) { } Player* initiator; Player* opponent; @@ -294,6 +297,7 @@ struct DuelInfo time_t startTime; time_t outOfBound; bool isMounted; + bool isCompleted; }; struct Areas @@ -314,7 +318,7 @@ enum RuneCooldowns RUNE_MISS_COOLDOWN = 1500 // cooldown applied on runes when the spell misses }; -enum RuneType +enum RuneType : uint8 { RUNE_BLOOD = 0, RUNE_UNHOLY = 1, @@ -348,7 +352,7 @@ struct Runes struct EnchantDuration { - EnchantDuration() : item(NULL), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) { } + EnchantDuration() : item(nullptr), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) { } EnchantDuration(Item* _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot), leftduration(_leftduration){ ASSERT(item); } @@ -414,50 +418,48 @@ enum PlayerFlags PLAYER_FLAGS_UNK31 = 0x80000000 }; -// used for PLAYER__FIELD_KNOWN_TITLES field (uint64), (1<<bit_index) without (-1) -// can't use enum for uint64 values -#define PLAYER_TITLE_DISABLED UI64LIT(0x0000000000000000) -#define PLAYER_TITLE_NONE UI64LIT(0x0000000000000001) -#define PLAYER_TITLE_PRIVATE UI64LIT(0x0000000000000002) // 1 -#define PLAYER_TITLE_CORPORAL UI64LIT(0x0000000000000004) // 2 -#define PLAYER_TITLE_SERGEANT_A UI64LIT(0x0000000000000008) // 3 -#define PLAYER_TITLE_MASTER_SERGEANT UI64LIT(0x0000000000000010) // 4 -#define PLAYER_TITLE_SERGEANT_MAJOR UI64LIT(0x0000000000000020) // 5 -#define PLAYER_TITLE_KNIGHT UI64LIT(0x0000000000000040) // 6 -#define PLAYER_TITLE_KNIGHT_LIEUTENANT UI64LIT(0x0000000000000080) // 7 -#define PLAYER_TITLE_KNIGHT_CAPTAIN UI64LIT(0x0000000000000100) // 8 -#define PLAYER_TITLE_KNIGHT_CHAMPION UI64LIT(0x0000000000000200) // 9 -#define PLAYER_TITLE_LIEUTENANT_COMMANDER UI64LIT(0x0000000000000400) // 10 -#define PLAYER_TITLE_COMMANDER UI64LIT(0x0000000000000800) // 11 -#define PLAYER_TITLE_MARSHAL UI64LIT(0x0000000000001000) // 12 -#define PLAYER_TITLE_FIELD_MARSHAL UI64LIT(0x0000000000002000) // 13 -#define PLAYER_TITLE_GRAND_MARSHAL UI64LIT(0x0000000000004000) // 14 -#define PLAYER_TITLE_SCOUT UI64LIT(0x0000000000008000) // 15 -#define PLAYER_TITLE_GRUNT UI64LIT(0x0000000000010000) // 16 -#define PLAYER_TITLE_SERGEANT_H UI64LIT(0x0000000000020000) // 17 -#define PLAYER_TITLE_SENIOR_SERGEANT UI64LIT(0x0000000000040000) // 18 -#define PLAYER_TITLE_FIRST_SERGEANT UI64LIT(0x0000000000080000) // 19 -#define PLAYER_TITLE_STONE_GUARD UI64LIT(0x0000000000100000) // 20 -#define PLAYER_TITLE_BLOOD_GUARD UI64LIT(0x0000000000200000) // 21 -#define PLAYER_TITLE_LEGIONNAIRE UI64LIT(0x0000000000400000) // 22 -#define PLAYER_TITLE_CENTURION UI64LIT(0x0000000000800000) // 23 -#define PLAYER_TITLE_CHAMPION UI64LIT(0x0000000001000000) // 24 -#define PLAYER_TITLE_LIEUTENANT_GENERAL UI64LIT(0x0000000002000000) // 25 -#define PLAYER_TITLE_GENERAL UI64LIT(0x0000000004000000) // 26 -#define PLAYER_TITLE_WARLORD UI64LIT(0x0000000008000000) // 27 -#define PLAYER_TITLE_HIGH_WARLORD UI64LIT(0x0000000010000000) // 28 -#define PLAYER_TITLE_GLADIATOR UI64LIT(0x0000000020000000) // 29 -#define PLAYER_TITLE_DUELIST UI64LIT(0x0000000040000000) // 30 -#define PLAYER_TITLE_RIVAL UI64LIT(0x0000000080000000) // 31 -#define PLAYER_TITLE_CHALLENGER UI64LIT(0x0000000100000000) // 32 -#define PLAYER_TITLE_SCARAB_LORD UI64LIT(0x0000000200000000) // 33 -#define PLAYER_TITLE_CONQUEROR UI64LIT(0x0000000400000000) // 34 -#define PLAYER_TITLE_JUSTICAR UI64LIT(0x0000000800000000) // 35 -#define PLAYER_TITLE_CHAMPION_OF_THE_NAARU UI64LIT(0x0000001000000000) // 36 -#define PLAYER_TITLE_MERCILESS_GLADIATOR UI64LIT(0x0000002000000000) // 37 -#define PLAYER_TITLE_OF_THE_SHATTERED_SUN UI64LIT(0x0000004000000000) // 38 -#define PLAYER_TITLE_HAND_OF_ADAL UI64LIT(0x0000008000000000) // 39 -#define PLAYER_TITLE_VENGEFUL_GLADIATOR UI64LIT(0x0000010000000000) // 40 +enum PlayerBytesOffsets +{ + PLAYER_BYTES_OFFSET_SKIN_ID = 0, + PLAYER_BYTES_OFFSET_FACE_ID = 1, + PLAYER_BYTES_OFFSET_HAIR_STYLE_ID = 2, + PLAYER_BYTES_OFFSET_HAIR_COLOR_ID = 3 +}; + +enum PlayerBytes2Offsets +{ + PLAYER_BYTES_2_OFFSET_FACIAL_STYLE = 0, + PLAYER_BYTES_2_OFFSET_PARTY_TYPE = 1, + PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS = 2, + PLAYER_BYTES_2_OFFSET_REST_STATE = 3 +}; + +enum PlayerBytes3Offsets +{ + PLAYER_BYTES_3_OFFSET_GENDER = 0, + PLAYER_BYTES_3_OFFSET_INEBRIATION = 1, + PLAYER_BYTES_3_OFFSET_PVP_TITLE = 2, + PLAYER_BYTES_3_OFFSET_ARENA_FACTION = 3 +}; + +enum PlayerFieldBytesOffsets +{ + PLAYER_FIELD_BYTES_OFFSET_FLAGS = 0, + PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL = 1, + PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES = 2, + PLAYER_FIELD_BYTES_OFFSET_LIFETIME_MAX_PVP_RANK = 3 +}; + +enum PlayerFieldBytes2Offsets +{ + PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID = 0, // uint16! + PLAYER_FIELD_BYTES_2_OFFSET_IGNORE_POWER_REGEN_PREDICTION_MASK = 2, + PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION = 3 +}; + +static_assert((PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID & 1) == 0, "PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID must be aligned to 2 byte boundary"); + +#define PLAYER_BYTES_2_OVERRIDE_SPELLS_UINT16_OFFSET (PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID / 2) #define KNOWN_TITLES_SIZE 3 #define MAX_TITLE_INDEX (KNOWN_TITLES_SIZE*64) // 3 uint64 fields @@ -583,7 +585,7 @@ enum PlayerSlots #define INVENTORY_SLOT_BAG_0 255 -enum EquipmentSlots // 19 slots +enum EquipmentSlots : uint8 // 19 slots { EQUIPMENT_SLOT_START = 0, EQUIPMENT_SLOT_HEAD = 0, @@ -608,13 +610,13 @@ enum EquipmentSlots // 19 slots EQUIPMENT_SLOT_END = 19 }; -enum InventorySlots // 4 slots +enum InventorySlots : uint8 // 4 slots { INVENTORY_SLOT_BAG_START = 19, INVENTORY_SLOT_BAG_END = 23 }; -enum InventoryPackSlots // 16 slots +enum InventoryPackSlots : uint8 // 16 slots { INVENTORY_SLOT_ITEM_START = 23, INVENTORY_SLOT_ITEM_END = 39 @@ -639,7 +641,7 @@ enum BuyBackSlots // 12 slots BUYBACK_SLOT_END = 86 }; -enum KeyRingSlots // 32 slots +enum KeyRingSlots : uint8 // 32 slots { KEYRING_SLOT_START = 86, KEYRING_SLOT_END = 118 @@ -749,7 +751,7 @@ enum TeleportToOptions }; /// Type of environmental damages -enum EnviromentalDamage +enum EnviromentalDamage : uint8 { DAMAGE_EXHAUSTED = 0, DAMAGE_DROWNING = 1, @@ -832,7 +834,7 @@ enum PlayerDelayedOperations // Player summoning auto-decline time (in secs) #define MAX_PLAYER_SUMMON_DELAY (2*MINUTE) // Maximum money amount : 2^31 - 1 -extern uint32 const MAX_MONEY_AMOUNT; +TC_GAME_API extern uint32 const MAX_MONEY_AMOUNT; enum BindExtensionState { @@ -854,7 +856,7 @@ struct InstancePlayerBind EXTENDED - won't be promoted to EXPIRED at next reset period, will instead be promoted to NORMAL */ BindExtensionState extendState; - InstancePlayerBind() : save(NULL), perm(false), extendState(EXTEND_STATE_NORMAL) { } + InstancePlayerBind() : save(nullptr), perm(false), extendState(EXTEND_STATE_NORMAL) { } }; struct AccessRequirement @@ -901,7 +903,7 @@ enum ReferAFriendError ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S = 0x0D }; -enum PlayerRestState +enum PlayerRestState : uint8 { REST_STATE_RESTED = 0x01, REST_STATE_NOT_RAF_LINKED = 0x02, @@ -918,7 +920,7 @@ enum PlayerCommandStates CHEAT_WATERWALK = 0x10 }; -class PlayerTaxi +class TC_GAME_API PlayerTaxi { public: PlayerTaxi(); @@ -1013,15 +1015,29 @@ struct TradeStatusInfo uint8 Slot; }; -class Player : public Unit, public GridObject<Player> +struct ResurrectionData +{ + ObjectGuid GUID; + WorldLocation Location; + uint32 Health; + uint32 Mana; + uint32 Aura; +}; + +#define SPELL_DK_RAISE_ALLY 46619 + +class TC_GAME_API Player : public Unit, public GridObject<Player> { friend class WorldSession; + friend class CinematicMgr; friend void Item::AddToUpdateQueueOf(Player* player); friend void Item::RemoveFromUpdateQueueOf(Player* player); public: explicit Player(WorldSession* session); ~Player(); + PlayerAI* AI() const { return reinterpret_cast<PlayerAI*>(i_AI); } + void CleanupsBeforeDelete(bool finalCleanup = true) override; void AddToWorld() override; @@ -1038,7 +1054,8 @@ class Player : public Unit, public GridObject<Player> bool TeleportTo(WorldLocation const &loc, uint32 options = 0); bool TeleportToBGEntryPoint(); - void SetSummonPoint(uint32 mapid, float x, float y, float z); + bool HasSummonPending() const; + void SendSummonRequestFrom(Unit* summoner); void SummonIfPossible(bool agree); bool Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo); @@ -1058,12 +1075,12 @@ class Player : public Unit, public GridObject<Player> void SendInitialPacketsBeforeAddToMap(); void SendInitialPacketsAfterAddToMap(); - void SendSupercededSpell(uint32 oldSpell, uint32 newSpell); - void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0); - void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome); + void SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const; + void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0) const; + void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const; - bool CanInteractWithQuestGiver(Object* questGiver); - Creature* GetNPCIfCanInteractWith(ObjectGuid const& guid, uint32 npcflagmask); + bool CanInteractWithQuestGiver(Object* questGiver) const; + Creature* GetNPCIfCanInteractWith(ObjectGuid const& guid, uint32 npcflagmask) const; GameObject* GetGameObjectIfCanInteractWith(ObjectGuid const& guid) const; GameObject* GetGameObjectIfCanInteractWith(ObjectGuid const& guid, GameobjectTypes type) const; @@ -1074,16 +1091,16 @@ class Player : public Unit, public GridObject<Player> uint8 GetChatTag() const; std::string autoReplyMsg; - uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin=NULL); + uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin = nullptr) const; - PlayerSocial *GetSocial() { return m_social; } + PlayerSocial *GetSocial() const { return m_social; } PlayerTaxi m_taxi; void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); } - bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = NULL, uint32 spellid = 0); + bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = nullptr, uint32 spellid = 0); bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 0); void CleanupAfterTaxiFlight(); - void ContinueTaxiFlight(); + void ContinueTaxiFlight() const; // mount_id can be used in scripting calls bool isAcceptWhispers() const { return (m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS) != 0; } void SetAcceptWhispers(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; } @@ -1136,12 +1153,16 @@ class Player : public Unit, public GridObject<Player> /// Handles said message in regular chat based on declared language and in config pre-defined Range. void Say(std::string const& text, Language language, WorldObject const* = nullptr) override; + void Say(uint32 textId, WorldObject const* target = nullptr) override; /// Handles yelled message in regular chat based on declared language and in config pre-defined Range. void Yell(std::string const& text, Language language, WorldObject const* = nullptr) override; + void Yell(uint32 textId, WorldObject const* target = nullptr) override; /// Outputs an universal text which is supposed to be an action. void TextEmote(std::string const& text, WorldObject const* = nullptr, bool = false) override; + void TextEmote(uint32 textId, WorldObject const* target = nullptr, bool isBossEmote = false) override; /// Handles whispers from Addons and players based on sender, receiver's guid and language. void Whisper(std::string const& text, Language language, Player* receiver, bool = false) override; + void Whisper(uint32 textId, Player* target, bool isBossWhisper = false) override; /*********************************************************/ /*** STORAGE SYSTEM ***/ @@ -1150,8 +1171,8 @@ class Player : public Unit, public GridObject<Player> void SetVirtualItemSlot(uint8 i, Item* item); void SetSheath(SheathState sheathed) override; // overwrite Unit version uint8 FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const; - uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = NULL) const; - uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const; + uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = nullptr) const; + uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; Item* GetItemByGuid(ObjectGuid guid) const; Item* GetItemByEntry(uint32 entry) const; Item* GetItemByPos(uint16 pos) const; @@ -1169,18 +1190,18 @@ class Player : public Unit, public GridObject<Player> static bool IsBagPos(uint16 pos); static bool IsBankPos(uint16 pos) { return IsBankPos(pos >> 8, pos & 255); } static bool IsBankPos(uint8 bag, uint8 slot); - bool IsValidPos(uint16 pos, bool explicit_pos) { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } - bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos); - uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); } - void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); } + bool IsValidPos(uint16 pos, bool explicit_pos) const { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } + bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) const; + uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS); } + void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS, count); } bool HasItemCount(uint32 item, uint32 count = 1, bool inBankAlso = false) const; - bool HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem = NULL) const; + bool HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem = nullptr) const; bool CanNoReagentCast(SpellInfo const* spellInfo) const; bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; InventoryResult CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory = NULL) const { return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem, NULL, itemLimitCategory); } InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, uint32* itemLimitCategory = NULL) const { return CanTakeMoreSimilarItems(entry, count, NULL, NULL, itemLimitCategory); } - InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = NULL) const; + InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = nullptr) const; InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const; InventoryResult CanStoreItems(Item** items, int count, uint32* itemLimitCategory) const; InventoryResult CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const; @@ -1207,7 +1228,7 @@ class Player : public Unit, public GridObject<Player> void StoreLootItem(uint8 lootSlot, Loot* loot); InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL, uint32* itemLimitCategory = NULL) const; - InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = NULL, bool swap = false, uint32* no_space_count = NULL) const; + InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = nullptr, bool swap = false, uint32* no_space_count = nullptr) const; void AddRefundReference(ObjectGuid it); void DeleteRefundReference(ObjectGuid it); @@ -1238,9 +1259,9 @@ class Player : public Unit, public GridObject<Player> Item* GetItemFromBuyBackSlot(uint32 slot); void RemoveItemFromBuyBackSlot(uint32 slot, bool del); uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END-KEYRING_SLOT_START; } - void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = NULL, uint32 itemid = 0); - void SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param); - void SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param); + void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = nullptr, uint32 itemid = 0) const; + void SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) const; + void SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param) const; void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; } void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; } uint32 GetWeaponProficiency() const { return m_WeaponProficiency; } @@ -1257,6 +1278,8 @@ class Player : public Unit, public GridObject<Player> TradeData* GetTradeData() const { return m_trade; } void TradeCancel(bool sendback); + CinematicMgr* GetCinematicMgr() const { return _cinematicMgr; } + void UpdateEnchantTime(uint32 time); void UpdateSoulboundTradeItems(); void AddTradeableItem(Item* item); @@ -1302,34 +1325,35 @@ class Player : public Unit, public GridObject<Player> void PrepareQuestMenu(ObjectGuid guid); void SendPreparedQuest(ObjectGuid guid); bool IsActiveQuest(uint32 quest_id) const; - Quest const* GetNextQuest(ObjectGuid guid, Quest const* quest); + Quest const* GetNextQuest(ObjectGuid guid, Quest const* quest) const; bool CanSeeStartQuest(Quest const* quest); bool CanTakeQuest(Quest const* quest, bool msg); - bool CanAddQuest(Quest const* quest, bool msg); + bool CanAddQuest(Quest const* quest, bool msg) const; bool CanCompleteQuest(uint32 quest_id); bool CanCompleteRepeatableQuest(Quest const* quest); bool CanRewardQuest(Quest const* quest, bool msg); bool CanRewardQuest(Quest const* quest, uint32 reward, bool msg); void AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver); void AddQuest(Quest const* quest, Object* questGiver); + void AbandonQuest(uint32 quest_id); void CompleteQuest(uint32 quest_id); void IncompleteQuest(uint32 quest_id); void RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce = true); void FailQuest(uint32 quest_id); bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const; - bool SatisfyQuestLevel(Quest const* qInfo, bool msg); - bool SatisfyQuestLog(bool msg); + bool SatisfyQuestLevel(Quest const* qInfo, bool msg) const; + bool SatisfyQuestLog(bool msg) const; bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg); bool SatisfyQuestClass(Quest const* qInfo, bool msg) const; - bool SatisfyQuestRace(Quest const* qInfo, bool msg); + bool SatisfyQuestRace(Quest const* qInfo, bool msg) const; bool SatisfyQuestReputation(Quest const* qInfo, bool msg); - bool SatisfyQuestStatus(Quest const* qInfo, bool msg); + bool SatisfyQuestStatus(Quest const* qInfo, bool msg) const; bool SatisfyQuestConditions(Quest const* qInfo, bool msg); - bool SatisfyQuestTimed(Quest const* qInfo, bool msg); + bool SatisfyQuestTimed(Quest const* qInfo, bool msg) const; bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg); - bool SatisfyQuestNextChain(Quest const* qInfo, bool msg); + bool SatisfyQuestNextChain(Quest const* qInfo, bool msg) const; bool SatisfyQuestPrevChain(Quest const* qInfo, bool msg); - bool SatisfyQuestDay(Quest const* qInfo, bool msg); + bool SatisfyQuestDay(Quest const* qInfo, bool msg) const; bool SatisfyQuestWeek(Quest const* qInfo, bool msg); bool SatisfyQuestMonth(Quest const* qInfo, bool msg); bool SatisfyQuestSeasonal(Quest const* qInfo, bool msg); @@ -1340,10 +1364,11 @@ class Player : public Unit, public GridObject<Player> void SetQuestStatus(uint32 questId, QuestStatus status, bool update = true); void RemoveActiveQuest(uint32 questId, bool update = true); void RemoveRewardedQuest(uint32 questId, bool update = true); - void SendQuestUpdate(uint32 questId); + void SendQuestUpdate(); QuestGiverStatus GetQuestDialogStatus(Object* questGiver); void SetDailyQuestStatus(uint32 quest_id); + bool IsDailyQuestDone(uint32 quest_id); void SetWeeklyQuestStatus(uint32 quest_id); void SetMonthlyQuestStatus(uint32 quest_id); void SetSeasonalQuestStatus(uint32 quest_id); @@ -1364,7 +1389,7 @@ class Player : public Unit, public GridObject<Player> void SetQuestSlotTimer(uint16 slot, uint32 timer); void SwapQuestSlot(uint16 slot1, uint16 slot2); - uint16 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry); + uint16 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) const; void AreaExploredOrEventHappens(uint32 questId); void GroupEventHappens(uint32 questId, WorldObject const* pEventObject); void ItemAddedQuestCheck(uint32 entry, uint32 count); @@ -1382,16 +1407,17 @@ class Player : public Unit, public GridObject<Player> void UpdateForQuestWorldObjects(); bool CanShareQuest(uint32 questId) const; - void SendQuestComplete(uint32 questId); - void SendQuestReward(Quest const* quest, uint32 XP); - void SendQuestFailed(uint32 questId, InventoryResult reason = EQUIP_ERR_OK); - void SendQuestTimerFailed(uint32 questId); + void SendQuestComplete(uint32 questId) const; + void SendQuestReward(Quest const* quest, uint32 XP) const; + void SendQuestFailed(uint32 questId, InventoryResult reason = EQUIP_ERR_OK) const; + void SendQuestTimerFailed(uint32 questId) const; void SendCanTakeQuestResponse(QuestFailedReason msg) const; - void SendQuestConfirmAccept(Quest const* quest, Player* pReceiver); - void SendPushToPartyResponse(Player* player, uint8 msg); - void SendQuestUpdateAddItem(Quest const* quest, uint32 itemIdx, uint16 count); + void SendQuestConfirmAccept(Quest const* quest, Player* pReceiver) const; + void SendPushToPartyResponse(Player* player, uint8 msg) const; + void SendQuestUpdateAddItem(Quest const* quest, uint32 itemIdx, uint16 count) const; void SendQuestUpdateAddCreatureOrGo(Quest const* quest, ObjectGuid guid, uint32 creatureOrGOIdx, uint16 oldCount, uint16 addCount); void SendQuestUpdateAddPlayer(Quest const* quest, uint16 oldCount, uint16 addCount); + void SendQuestGiverStatusMultiple(); ObjectGuid GetDivider() const { return m_divider; } void SetDivider(ObjectGuid guid) { m_divider = guid; } @@ -1427,10 +1453,9 @@ class Player : public Unit, public GridObject<Player> void SaveToDB(bool create = false); void SaveInventoryAndGoldToDB(SQLTransaction& trans); // fast save function for item/money cheating preventing - void SaveGoldToDB(SQLTransaction& trans); + void SaveGoldToDB(SQLTransaction& trans) const; static void SetUInt32ValueInArray(Tokenizer& data, uint16 index, uint32 value); - static void SetFloatValueInArray(Tokenizer& data, uint16 index, float value); static void Customize(CharacterCustomizeInfo const* customizeInfo, SQLTransaction& trans); static void SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, SQLTransaction& trans); @@ -1441,10 +1466,9 @@ class Player : public Unit, public GridObject<Player> bool m_mailsLoaded; bool m_mailsUpdated; - void SetBindPoint(ObjectGuid guid); - void SendTalentWipeConfirm(ObjectGuid guid); + void SetBindPoint(ObjectGuid guid) const; + void SendTalentWipeConfirm(ObjectGuid guid) const; void ResetPetTalents(); - void CalcRage(uint32 damage, bool attacker); void RegenerateAll(); void Regenerate(Powers power); void RegenerateHealth(); @@ -1472,13 +1496,13 @@ class Player : public Unit, public GridObject<Player> uint8 GetComboPoints() const { return m_comboPoints; } ObjectGuid GetComboTarget() const { return m_comboTarget; } - void AddComboPoints(Unit* target, int8 count, Spell* spell = NULL); + void AddComboPoints(Unit* target, int8 count, Spell* spell = nullptr); void GainSpellComboPoints(int8 count); void ClearComboPoints(); void SendComboPoints(); - void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, ObjectGuid::LowType item_guid = 0, uint32 item_count = 0); - void SendNewMail(); + void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, ObjectGuid::LowType item_guid = 0, uint32 item_count = 0) const; + void SendNewMail() const; void UpdateNextMailTimeAndUnreads(); void AddNewMailDeliverTime(time_t deliver_time); bool IsMailsLoaded() const { return m_mailsLoaded; } @@ -1509,19 +1533,19 @@ class Player : public Unit, public GridObject<Player> void AddMItem(Item* it); bool RemoveMItem(uint32 id); - void SendOnCancelExpectedVehicleRideAura(); + void SendOnCancelExpectedVehicleRideAura() const; void PetSpellInitialize(); void CharmSpellInitialize(); void PossessSpellInitialize(); void VehicleSpellInitialize(); - void SendRemoveControlBar(); + void SendRemoveControlBar() const; bool HasSpell(uint32 spell) const override; bool HasActiveSpell(uint32 spell) const; // show in spellbook TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell) const; bool IsSpellFitByClassAndRace(uint32 spell_id) const; bool IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const; - void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask); + void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const; void SendInitialSpells(); bool AddSpell(uint32 spellId, bool active, bool learning, bool dependent, bool disabled, bool loading = false, uint32 fromSkill = 0); void LearnSpell(uint32 spell_id, bool dependent, uint32 fromSkill = 0); @@ -1537,7 +1561,7 @@ class Player : public Unit, public GridObject<Player> void RemoveTemporarySpell(uint32 spellId); void SetReputation(uint32 factionentry, uint32 value); uint32 GetReputation(uint32 factionentry) const; - std::string const& GetGuildName(); + std::string const& GetGuildName() const; uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); } void SetFreeTalentPoints(uint32 points); bool ResetTalents(bool no_cost = false); @@ -1576,26 +1600,40 @@ class Player : public Unit, public GridObject<Player> PlayerSpellMap & GetSpellMap() { return m_spells; } void AddSpellMod(SpellModifier* mod, bool apply); - bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell = NULL); - template <class T> T ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell* spell = NULL); + bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell = nullptr) const; + template <class T> + void ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell = nullptr); void RemoveSpellMods(Spell* spell); - void RestoreSpellMods(Spell* spell, uint32 ownerAuraId = 0, Aura* aura = NULL); - void RestoreAllSpellMods(uint32 ownerAuraId = 0, Aura* aura = NULL); + void RestoreSpellMods(Spell* spell, uint32 ownerAuraId = 0, Aura* aura = nullptr); + void RestoreAllSpellMods(uint32 ownerAuraId = 0, Aura* aura = nullptr); void DropModCharge(SpellModifier* mod, Spell* spell); void SetSpellModTakingSpell(Spell* spell, bool apply); void RemoveArenaSpellCooldowns(bool removeActivePetCooldowns = false); uint32 GetLastPotionId() const { return m_lastPotionId; } void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; } - void UpdatePotionCooldown(Spell* spell = NULL); + void UpdatePotionCooldown(Spell* spell = nullptr); - void setResurrectRequestData(ObjectGuid guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana); - void clearResurrectRequestData(); - bool isResurrectRequestedBy(ObjectGuid guid) const { return !m_resurrectGUID.IsEmpty() && m_resurrectGUID == guid; } - bool isResurrectRequested() const { return !m_resurrectGUID.IsEmpty(); } + void SetResurrectRequestData(Unit* caster, uint32 health, uint32 mana, uint32 appliedAura); + + void ClearResurrectRequestData() + { + _resurrectionData.reset(); + } + + bool IsResurrectRequestedBy(ObjectGuid const& guid) const + { + if (!IsResurrectRequested()) + return false; + + return !_resurrectionData->GUID.IsEmpty() && _resurrectionData->GUID == guid; + } + + bool IsResurrectRequested() const { return _resurrectionData.get() != nullptr; } void ResurrectUsingRequestData(); + void ResurrectUsingRequestDataImpl(); - uint8 getCinematic() { return m_cinematic; } + uint8 getCinematic() const { return m_cinematic; } void setCinematic(uint8 cine) { m_cinematic = cine; } ActionButton* addActionButton(uint8 button, uint32 action, uint8 type); @@ -1603,11 +1641,11 @@ class Player : public Unit, public GridObject<Player> ActionButton const* GetActionButton(uint8 button); void SendInitialActionButtons() const { SendActionButtons(1); } void SendActionButtons(uint32 state) const; - bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type); + bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) const; PvPInfo pvpInfo; void UpdatePvPState(bool onlyFFA = false); - void SetPvP(bool state); + void SetPvP(bool state) override; void UpdatePvP(bool state, bool override=false); void UpdateZone(uint32 newZone, uint32 newArea); void UpdateArea(uint32 newArea); @@ -1633,7 +1671,7 @@ class Player : public Unit, public GridObject<Player> bool IsInSameGroupWith(Player const* p) const; bool IsInSameRaidWith(Player const* p) const; void UninviteFromGroup(); - static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, const char* reason = NULL); + static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, const char* reason = nullptr); void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } void SendUpdateToOutOfRangeGroupMembers(); @@ -1700,13 +1738,13 @@ class Player : public Unit, public GridObject<Player> void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) override; void UpdateDefenseBonusesMod(); - inline void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);} - float GetMeleeCritFromAgility(); - void GetDodgeFromAgility(float &diminishing, float &nondiminishing); + void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);} + float GetMeleeCritFromAgility() const; + void GetDodgeFromAgility(float &diminishing, float &nondiminishing) const; float GetMissPercentageFromDefence() const; - float GetSpellCritFromIntellect(); - float OCTRegenHPPerSpirit(); - float OCTRegenMPPerSpirit(); + float GetSpellCritFromIntellect() const; + float OCTRegenHPPerSpirit() const; + float OCTRegenMPPerSpirit() const; float GetRatingMultiplier(CombatRating cr) const; float GetRatingBonusValue(CombatRating cr) const; uint32 GetBaseSpellPowerBonus() const { return m_baseSpellPower; } @@ -1744,26 +1782,26 @@ class Player : public Unit, public GridObject<Player> void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override; void DestroyForPlayer(Player* target, bool onDeath = false) const override; - void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend = false, float group_rate=1.0f); + void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend = false, float group_rate=1.0f) const; // notifiers - void SendAttackSwingCantAttack(); - void SendAttackSwingCancelAttack(); - void SendAttackSwingDeadTarget(); - void SendAttackSwingNotInRange(); - void SendAttackSwingBadFacingAttack(); + void SendAttackSwingCantAttack() const; + void SendAttackSwingCancelAttack() const; + void SendAttackSwingDeadTarget() const; + void SendAttackSwingNotInRange() const; + void SendAttackSwingBadFacingAttack() const; void SendAutoRepeatCancel(Unit* target); - void SendExplorationExperience(uint32 Area, uint32 Experience); + void SendExplorationExperience(uint32 Area, uint32 Experience) const; - void SendDungeonDifficulty(bool IsInGroup); - void SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty = -1); + void SendDungeonDifficulty(bool IsInGroup) const; + void SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty = -1) const; void ResetInstances(uint8 method, bool isRaid); - void SendResetInstanceSuccess(uint32 MapId); - void SendResetInstanceFailed(uint32 reason, uint32 MapId); - void SendResetFailedNotify(uint32 mapid); + void SendResetInstanceSuccess(uint32 MapId) const; + void SendResetInstanceFailed(uint32 reason, uint32 MapId) const; + void SendResetFailedNotify(uint32 mapid) const; - virtual bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; - bool UpdatePosition(const Position &pos, bool teleport = false) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } + bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; + bool UpdatePosition(const Position &pos, bool teleport = false) override { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } void UpdateUnderwaterState(Map* m, float x, float y, float z) override; void SendMessageToSet(WorldPacket* data, bool self) override { SendMessageToSetInRange(data, GetVisibilityRange(), self); } @@ -1784,14 +1822,7 @@ class Player : public Unit, public GridObject<Player> void ResurrectPlayer(float restore_percent, bool applySickness = false); void BuildPlayerRepop(); void RepopAtGraveyard(); - void SendGhoulResurrectRequest(Player* target); - bool IsValidGhoulResurrectRequest(ObjectGuid guid) - { - return !m_ghoulResurrectPlayerGUID.IsEmpty() && m_ghoulResurrectPlayerGUID == guid; - } - void GhoulResurrect(); - void SetGhoulResurrectGhoulGUID(ObjectGuid guid) { m_ghoulResurrectGhoulGUID = guid; } - ObjectGuid GetGhoulResurrectGhoulGUID() { return m_ghoulResurrectGhoulGUID; } + void RemoveGhoul(); void DurabilityLossAll(double percent, bool inventory); @@ -1804,11 +1835,11 @@ class Player : public Unit, public GridObject<Player> void UpdateMirrorTimers(); void StopMirrorTimers(); - bool IsMirrorTimerActive(MirrorTimerType type); + bool IsMirrorTimerActive(MirrorTimerType type) const; void SetMovement(PlayerMovementType pType); - bool CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone); + bool CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone) const; void JoinedChannel(Channel* c); void LeftChannel(Channel* c); @@ -1893,14 +1924,14 @@ class Player : public Unit, public GridObject<Player> //End of PvP System void SetDrunkValue(uint8 newDrunkValue, uint32 itemId = 0); - uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, 1); } + uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION); } static DrunkenState GetDrunkenstateByValue(uint8 value); uint32 GetDeathTimer() const { return m_deathTimer; } uint32 GetCorpseReclaimDelay(bool pvp) const; void UpdateCorpseReclaimDelay(); - int32 CalculateCorpseReclaimDelay(bool load = false); - void SendCorpseReclaimDelay(uint32 delay); + int32 CalculateCorpseReclaimDelay(bool load = false) const; + void SendCorpseReclaimDelay(uint32 delay) const; uint32 GetShieldBlockValue() const override; // overwrite Unit version (virtual) bool CanParry() const { return m_canParry; } @@ -1933,7 +1964,7 @@ class Player : public Unit, public GridObject<Player> void _ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale = false); void _ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, ScalingStatValuesEntry const* ssv, bool apply); void _ApplyAmmoBonuses(); - bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot); + bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) const; void ToggleMetaGemsActive(uint8 exceptslot, bool apply); void CorrectMetaGemEnchants(uint8 slot, bool apply); void InitDataForForm(bool reapplyMods = false); @@ -1950,21 +1981,21 @@ class Player : public Unit, public GridObject<Player> void DeleteEquipmentSet(uint64 setGuid); void SendInitWorldStates(uint32 zone, uint32 area); - void SendUpdateWorldState(uint32 Field, uint32 Value); - void SendDirectMessage(WorldPacket* data); - void SendBGWeekendWorldStates(); - void SendBattlefieldWorldStates(); + void SendUpdateWorldState(uint32 Field, uint32 Value) const; + void SendDirectMessage(WorldPacket const* data) const; + void SendBGWeekendWorldStates() const; + void SendBattlefieldWorldStates() const; - void SendAurasForTarget(Unit* target); + void SendAurasForTarget(Unit* target) const; PlayerMenu* PlayerTalkClass; std::vector<ItemSetEffect*> ItemSetEff; void SendLoot(ObjectGuid guid, LootType loot_type); - void SendLootError(ObjectGuid guid, LootError error); - void SendLootRelease(ObjectGuid guid); - void SendNotifyLootItemRemoved(uint8 lootSlot); - void SendNotifyLootMoneyRemoved(); + void SendLootError(ObjectGuid guid, LootError error) const; + void SendLootRelease(ObjectGuid guid) const; + void SendNotifyLootItemRemoved(uint8 lootSlot) const; + void SendNotifyLootMoneyRemoved() const; /*********************************************************/ /*** BATTLEGROUND SYSTEM ***/ @@ -1985,7 +2016,7 @@ class Player : public Unit, public GridObject<Player> void SetBattlegroundId(uint32 val, BattlegroundTypeId bgTypeId); uint32 AddBattlegroundQueueId(BattlegroundQueueTypeId val); - bool HasFreeBattlegroundQueueId(); + bool HasFreeBattlegroundQueueId() const; void RemoveBattlegroundQueueId(BattlegroundQueueTypeId val); void SetInviteForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId, uint32 instanceId); bool IsInvitedForBattlegroundInstance(uint32 instanceId) const; @@ -2002,10 +2033,10 @@ class Player : public Unit, public GridObject<Player> void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); } bool GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const; - bool isTotalImmunity(); - bool CanUseBattlegroundObject(GameObject* gameobject); - bool isTotalImmune(); - bool CanCaptureTowerPoint(); + bool isTotalImmunity() const; + bool CanUseBattlegroundObject(GameObject* gameobject) const; + bool isTotalImmune() const; + bool CanCaptureTowerPoint() const; bool GetRandomWinner() const { return m_IsBGRandomWinner; } void SetRandomWinner(bool isWinner); @@ -2016,13 +2047,13 @@ class Player : public Unit, public GridObject<Player> OutdoorPvP* GetOutdoorPvP() const; // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise - bool IsOutdoorPvPActive(); + bool IsOutdoorPvPActive() const; /*********************************************************/ /*** ENVIROMENTAL SYSTEM ***/ /*********************************************************/ - bool IsImmuneToEnvironmentalDamage(); + bool IsImmuneToEnvironmentalDamage() const; uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage); /*********************************************************/ @@ -2052,18 +2083,13 @@ class Player : public Unit, public GridObject<Player> void SetViewpoint(WorldObject* target, bool apply); WorldObject* GetViewpoint() const; void StopCastingCharm(); - void StopCastingBindSight(); + void StopCastingBindSight() const; uint32 GetSaveTimer() const { return m_nextSave; } void SetSaveTimer(uint32 timer) { m_nextSave = timer; } - // Recall position - uint32 m_recallMap; - float m_recallX; - float m_recallY; - float m_recallZ; - float m_recallO; - void SaveRecallPosition(); + void SaveRecallPosition() { m_recall_location.WorldRelocate(*this); } + void Recall() { TeleportTo(m_recall_location); } void SetHomebind(WorldLocation const& loc, uint32 areaId); @@ -2079,13 +2105,13 @@ class Player : public Unit, public GridObject<Player> // currently visible objects at player client GuidUnorderedSet m_clientGUIDs; - bool HaveAtClient(WorldObject const* u) const; + bool HaveAtClient(Object const* u) const; bool IsNeverVisible() const override; bool IsVisibleGloballyFor(Player const* player) const; - void SendInitialVisiblePackets(Unit* target); + void SendInitialVisiblePackets(Unit* target) const; void UpdateObjectVisibility(bool forced = true) override; void UpdateVisibilityForPlayer(); void UpdateVisibilityOf(WorldObject* target); @@ -2100,8 +2126,8 @@ class Player : public Unit, public GridObject<Player> void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; } void RemoveAtLoginFlag(AtLoginFlags flags, bool persist = false); - bool isUsingLfg(); - bool inRandomLfgDungeon(); + bool isUsingLfg() const; + bool inRandomLfgDungeon() const; typedef std::set<uint32> DFQuestsDoneList; DFQuestsDoneList m_DFQuests; @@ -2113,8 +2139,10 @@ class Player : public Unit, public GridObject<Player> void ResummonPetTemporaryUnSummonedIfAny(); bool IsPetNeedBeTemporaryUnsummoned() const; - void SendCinematicStart(uint32 CinematicSequenceId); - void SendMovieStart(uint32 MovieId); + void SendCinematicStart(uint32 CinematicSequenceId) const; + void SendMovieStart(uint32 MovieId) const; + + uint32 DoRandomRoll(uint32 minimum, uint32 maximum); /*********************************************************/ /*** INSTANCE SYSTEM ***/ @@ -2152,10 +2180,10 @@ class Player : public Unit, public GridObject<Player> /*** GROUP SYSTEM ***/ /*********************************************************/ - Group* GetGroupInvite() { return m_groupInvite; } + Group* GetGroupInvite() const { return m_groupInvite; } void SetGroupInvite(Group* group) { m_groupInvite = group; } Group* GetGroup() { return m_group.getTarget(); } - const Group* GetGroup() const { return (const Group*)m_group.getTarget(); } + Group const* GetGroup() const { return const_cast<Group const*>(m_group.getTarget()); } GroupReference& GetGroupRef() { return m_group; } void SetGroup(Group* group, int8 subgroup = -1); uint8 GetSubGroup() const { return m_group.getSubGroup(); } @@ -2169,7 +2197,7 @@ class Player : public Unit, public GridObject<Player> // Battleground / Battlefield Group System void SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup = -1); void RemoveFromBattlegroundOrBattlefieldRaid(); - Group* GetOriginalGroup() { return m_originalGroup.getTarget(); } + Group* GetOriginalGroup() const { return m_originalGroup.getTarget(); } GroupReference& GetOriginalGroupRef() { return m_originalGroup; } uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); } void SetOriginalGroup(Group* group, int8 subgroup = -1); @@ -2202,8 +2230,8 @@ class Player : public Unit, public GridObject<Player> void RemoveRunesByAuraEffect(AuraEffect const* aura); void RestoreBaseRune(uint8 index); void ConvertRune(uint8 index, RuneType newType); - void ResyncRunes(uint8 count); - void AddRunePower(uint8 index); + void ResyncRunes(uint8 count) const; + void AddRunePower(uint8 index) const; void InitRunes(); void SendRespondInspectAchievements(Player* player) const; @@ -2227,7 +2255,7 @@ class Player : public Unit, public GridObject<Player> void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; } Spell* m_spellModTakingSpell; - float GetAverageItemLevel(); + float GetAverageItemLevel() const; bool isDebugAreaTriggers; void ClearWhisperWhiteList() { WhisperList.clear(); } @@ -2246,8 +2274,8 @@ class Player : public Unit, public GridObject<Player> //! Return collision height sent to client float GetCollisionHeight(bool mounted) const; - std::string GetMapAreaAndZoneString(); - std::string GetCoordsMapAreaAndZoneString(); + std::string GetMapAreaAndZoneString() const; + std::string GetCoordsMapAreaAndZoneString() const; protected: // Gamemaster whisper whitelist @@ -2338,9 +2366,9 @@ class Player : public Unit, public GridObject<Player> void _SaveSpells(SQLTransaction& trans); void _SaveEquipmentSets(SQLTransaction& trans); void _SaveBGData(SQLTransaction& trans); - void _SaveGlyphs(SQLTransaction& trans); + void _SaveGlyphs(SQLTransaction& trans) const; void _SaveTalents(SQLTransaction& trans); - void _SaveStats(SQLTransaction& trans); + void _SaveStats(SQLTransaction& trans) const; void _SaveInstanceTimeRestrictions(SQLTransaction& trans); /*********************************************************/ @@ -2350,7 +2378,7 @@ class Player : public Unit, public GridObject<Player> void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen); void StopMirrorTimer(MirrorTimerType Type); void HandleDrowning(uint32 time_diff); - int32 getMaxTimer(MirrorTimerType timer); + int32 getMaxTimer(MirrorTimerType timer) const; /*********************************************************/ /*** HONOR SYSTEM ***/ @@ -2421,13 +2449,7 @@ class Player : public Unit, public GridObject<Player> void ResetTimeSync(); void SendTimeSync(); - ObjectGuid m_resurrectGUID; - uint32 m_resurrectMap; - float m_resurrectX, m_resurrectY, m_resurrectZ; - uint32 m_resurrectHealth, m_resurrectMana; - - ObjectGuid m_ghoulResurrectPlayerGUID; - ObjectGuid m_ghoulResurrectGhoulGUID; + std::unique_ptr<ResurrectionData> _resurrectionData; WorldSession* m_session; @@ -2489,10 +2511,10 @@ class Player : public Unit, public GridObject<Player> // Player summoning time_t m_summon_expire; - uint32 m_summon_mapid; - float m_summon_x; - float m_summon_y; - float m_summon_z; + WorldLocation m_summon_location; + + // Recall position + WorldLocation m_recall_location; DeclinedName *m_declinedname; Runes *m_runes; @@ -2514,6 +2536,8 @@ class Player : public Unit, public GridObject<Player> Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update); Item* _LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields); + CinematicMgr* _cinematicMgr; + GuidSet m_refundableItems; void SendRefundInfo(Item* item); void RefundItem(Item* item); @@ -2533,8 +2557,6 @@ class Player : public Unit, public GridObject<Player> MapReference m_mapRef; - void UpdateCharmedAI(); - uint32 m_lastFallTime; float m_lastFallZ; @@ -2584,15 +2606,17 @@ class Player : public Unit, public GridObject<Player> WorldLocation _corpseLocation; }; -void AddItemsSetItem(Player* player, Item* item); -void RemoveItemsSetItem(Player* player, ItemTemplate const* proto); +TC_GAME_API void AddItemsSetItem(Player* player, Item* item); +TC_GAME_API void RemoveItemsSetItem(Player* player, ItemTemplate const* proto); // "the bodies of template functions must be made available in a header file" -template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell* spell) +template <class T> +void Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell /*= nullptr*/) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) - return 0; + return; + float totalmul = 1.0f; int32 totalflat = 0; @@ -2628,9 +2652,8 @@ template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &bas DropModCharge(mod, spell); } - float diff = (float)basevalue * (totalmul - 1.0f) + (float)totalflat; - basevalue = T((float)basevalue + diff); - return T(diff); + + basevalue = T(float(basevalue + totalflat) * totalmul); } #endif diff --git a/src/server/game/Entities/Player/SocialMgr.cpp b/src/server/game/Entities/Player/SocialMgr.cpp index ffb2d8a7dd8..809bdd0bf6f 100644 --- a/src/server/game/Entities/Player/SocialMgr.cpp +++ b/src/server/game/Entities/Player/SocialMgr.cpp @@ -195,6 +195,12 @@ SocialMgr::SocialMgr() { } SocialMgr::~SocialMgr() { } +SocialMgr* SocialMgr::instance() +{ + static SocialMgr instance; + return &instance; +} + void SocialMgr::GetFriendInfo(Player* player, ObjectGuid::LowType friendGUID, FriendInfo &friendInfo) { if (!player) diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index 8f8ed04b5fb..803301b95c7 100644 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -99,7 +99,7 @@ enum FriendsResult #define SOCIALMGR_FRIEND_LIMIT 50 #define SOCIALMGR_IGNORE_LIMIT 50 -class PlayerSocial +class TC_GAME_API PlayerSocial { friend class SocialMgr; public: @@ -128,11 +128,7 @@ class SocialMgr ~SocialMgr(); public: - static SocialMgr* instance() - { - static SocialMgr instance; - return &instance; - } + static SocialMgr* instance(); // Misc void RemovePlayerSocial(ObjectGuid::LowType guid) { m_socialMap.erase(guid); } diff --git a/src/server/game/Entities/Player/TradeData.h b/src/server/game/Entities/Player/TradeData.h index 276e6f3db1c..396d784fee7 100644 --- a/src/server/game/Entities/Player/TradeData.h +++ b/src/server/game/Entities/Player/TradeData.h @@ -31,7 +31,7 @@ enum TradeSlots class Item; class Player; -class TradeData +class TC_GAME_API TradeData { public: TradeData(Player* player, Player* trader) : diff --git a/src/server/game/Entities/Totem/Totem.h b/src/server/game/Entities/Totem/Totem.h index bbe7943f4b6..42be4525a0c 100644 --- a/src/server/game/Entities/Totem/Totem.h +++ b/src/server/game/Entities/Totem/Totem.h @@ -32,7 +32,7 @@ enum TotemType #define SENTRY_TOTEM_ENTRY 3968 -class Totem : public Minion +class TC_GAME_API Totem : public Minion { public: Totem(SummonPropertiesEntry const* properties, Unit* owner); diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index 5e5c6901471..0d97e120fff 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -92,7 +92,8 @@ bool Transport::Create(ObjectGuid::LowType guidlow, uint32 entry, uint32 mapid, SetGoType(GAMEOBJECT_TYPE_MO_TRANSPORT); SetGoAnimProgress(animprogress); SetName(goinfo->name); - UpdateRotationFields(0.0f, 1.0f); + SetWorldRotation(G3D::Quat()); + SetParentRotation(G3D::Quat()); m_model = CreateModel(); return true; diff --git a/src/server/game/Entities/Transport/Transport.h b/src/server/game/Entities/Transport/Transport.h index 987fbf70739..4cd20c8b613 100644 --- a/src/server/game/Entities/Transport/Transport.h +++ b/src/server/game/Entities/Transport/Transport.h @@ -25,7 +25,7 @@ struct CreatureData; -class Transport : public GameObject, public TransportBase +class TC_GAME_API Transport : public GameObject, public TransportBase { friend Transport* TransportMgr::CreateTransport(uint32, ObjectGuid::LowType, Map*); diff --git a/src/server/game/Entities/Unit/StatSystem.cpp b/src/server/game/Entities/Unit/StatSystem.cpp index 39a97d4f5a0..def6c382893 100644 --- a/src/server/game/Entities/Unit/StatSystem.cpp +++ b/src/server/game/Entities/Unit/StatSystem.cpp @@ -1152,7 +1152,7 @@ bool Guardian::UpdateStats(Stats stat) if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value AddPct(mod, spellInfo->Effects[EFFECT_0].CalcValue()); } } @@ -1321,7 +1321,7 @@ void Guardian::UpdateAttackPowerAndDamage(bool ranged) if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt { - SpellInfo const* sProto = sSpellMgr->EnsureSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value + SpellInfo const* sProto = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, sProto->Effects[1].CalcValue()); } } diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index 4454b344741..ac924f39a03 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -45,6 +45,7 @@ #include "PetAI.h" #include "Pet.h" #include "Player.h" +#include "PlayerAI.h" #include "QuestDef.h" #include "ReputationMgr.h" #include "SpellAuraEffects.h" @@ -458,12 +459,6 @@ void Unit::resetAttackTimer(WeaponAttackType type) m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]); } -float Unit::GetMeleeReach() const -{ - float reach = m_floatValues[UNIT_FIELD_COMBATREACH]; - return reach > MIN_MELEE_REACH ? reach : MIN_MELEE_REACH; -} - bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const { if (!obj || !IsInMap(obj) || !InSamePhase(obj)) @@ -480,7 +475,7 @@ bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const return distsq < maxdist * maxdist; } -bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const +bool Unit::IsWithinMeleeRange(Unit const* obj) const { if (!obj || !IsInMap(obj) || !InSamePhase(obj)) return false; @@ -490,10 +485,9 @@ bool Unit::IsWithinMeleeRange(const Unit* obj, float dist) const float dz = GetPositionZMinusOffset() - obj->GetPositionZMinusOffset(); float distsq = dx*dx + dy*dy + dz*dz; - float sizefactor = GetMeleeReach() + obj->GetMeleeReach(); - float maxdist = dist + sizefactor; + float maxdist = GetCombatReach() + obj->GetCombatReach() + 4.0f / 3.0f; - return distsq < maxdist * maxdist; + return distsq <= maxdist * maxdist; } void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const @@ -577,7 +571,7 @@ bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) cons void Unit::DealDamageMods(Unit* victim, uint32 &damage, uint32* absorb) { - if (!victim || !victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())) + if (!victim || !victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks())) { if (absorb) *absorb += damage; @@ -598,11 +592,14 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam if (victim->GetTypeId() == TYPEID_PLAYER && this != victim) { - // Signal to pets that their owner was attacked - Pet* pet = victim->ToPlayer()->GetPet(); + // Signal to pets that their owner was attacked - except when DOT. + if (damagetype != DOT) + { + Pet* pet = victim->ToPlayer()->GetPet(); - if (pet && pet->IsAlive()) - pet->AI()->OwnerAttackedBy(this); + if (pet && pet->IsAlive()) + pet->AI()->OwnerAttackedBy(this); + } if (victim->ToPlayer()->GetCommandStatus(CHEAT_GOD)) return 0; @@ -623,6 +620,17 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam else victim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TAKE_DAMAGE, 0); + // interrupt spells with SPELL_INTERRUPT_FLAG_ABORT_ON_DMG on absorbed damage (no dots) + if (!damage && damagetype != DOT && cleanDamage && cleanDamage->absorbed_damage) + if (victim != this && victim->GetTypeId() == TYPEID_PLAYER) + if (Spell* spell = victim->m_currentSpells[CURRENT_GENERIC_SPELL]) + if (spell->getState() == SPELL_STATE_PREPARING) + { + uint32 interruptFlags = spell->m_spellInfo->InterruptFlags; + if ((interruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG) != 0) + victim->InterruptNonMeleeSpells(false); + } + // We're going to call functions which can modify content of the list during iteration over it's elements // Let's copy the list so we can prevent iterator invalidation AuraEffectList vCopyDamageCopy(victim->GetAuraEffectsByType(SPELL_AURA_SHARE_DAMAGE_PCT)); @@ -1119,7 +1127,7 @@ void Unit::DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss) if (!victim) return; - if (!victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())) + if (!victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks())) return; SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(damageInfo->SpellID); @@ -1345,7 +1353,7 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) { Unit* victim = damageInfo->target; - if (!victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode())) + if (!victim->IsAlive() || victim->HasUnitState(UNIT_STATE_IN_FLIGHT) || (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks())) return; // Hmmmm dont like this emotes client must by self do all animations @@ -1354,7 +1362,8 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS) victim->HandleEmoteCommand(EMOTE_ONESHOT_PARRY_SHIELD); - if (damageInfo->TargetState == VICTIMSTATE_PARRY) + if (damageInfo->TargetState == VICTIMSTATE_PARRY && + (GetTypeId() != TYPEID_UNIT || (ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN) == 0)) { // Get attack timers float offtime = float(victim->getAttackTimer(OFF_ATTACK)); @@ -2043,7 +2052,7 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* victim, WeaponAttackTy MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const { - if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()) + if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks()) return MELEE_HIT_EVADE; int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(victim); @@ -2252,7 +2261,7 @@ float Unit::CalculateLevelPenalty(SpellInfo const* spellProto) const float LvlPenalty = 0.0f; if (spellProto->SpellLevel < 20) - LvlPenalty = 20.0f - spellProto->SpellLevel * 3.75f; + LvlPenalty = (20.0f - spellProto->SpellLevel) * 3.75f; float LvlFactor = (float(spellProto->SpellLevel) + 6.0f) / float(getLevel()); if (LvlFactor > 1.0f) LvlFactor = 1.0f; @@ -2386,37 +2395,19 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* victim, SpellInfo const* spellInfo if (roll < tmp) return SPELL_MISS_MISS; - // Chance resist mechanic (select max value from every mechanic spell effect) - int32 resist_mech = 0; - // Get effects mechanic and chance - for (uint8 eff = 0; eff < MAX_SPELL_EFFECTS; ++eff) - { - int32 effect_mech = spellInfo->GetEffectMechanic(eff); - if (effect_mech) - { - int32 temp = victim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); - if (resist_mech < temp * 100) - resist_mech = temp * 100; - } - } - // Roll chance - tmp += resist_mech; + // Chance resist mechanic + int32 resist_chance = victim->GetMechanicResistChance(spellInfo) * 100; + tmp += resist_chance; if (roll < tmp) return SPELL_MISS_RESIST; - bool canDodge = true; - bool canParry = true; - bool canBlock = spellInfo->HasAttribute(SPELL_ATTR3_BLOCKABLE_SPELL); - - // Same spells cannot be parry/dodge + // Same spells cannot be parried/dodged if (spellInfo->HasAttribute(SPELL_ATTR0_IMPOSSIBLE_DODGE_PARRY_BLOCK)) return SPELL_MISS_NONE; - // Chance resist mechanic - int32 resist_chance = victim->GetMechanicResistChance(spellInfo) * 100; - tmp += resist_chance; - if (roll < tmp) - return SPELL_MISS_RESIST; + bool canDodge = true; + bool canParry = true; + bool canBlock = spellInfo->HasAttribute(SPELL_ATTR3_BLOCKABLE_SPELL); // Ranged attacks can only miss, resist and deflect if (attType == RANGED_ATTACK) @@ -2655,7 +2646,7 @@ SpellMissInfo Unit::SpellHitResult(Unit* victim, SpellInfo const* spellInfo, boo return SPELL_MISS_NONE; // Return evade for units in evade mode - if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsInEvadeMode()) + if (victim->GetTypeId() == TYPEID_UNIT && victim->ToCreature()->IsEvadingAttacks()) return SPELL_MISS_EVADE; // Try victim reflect spell @@ -2853,6 +2844,15 @@ float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit* victi else crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); + AuraEffectList const& critChanceForCaster = victim->GetAuraEffectsByType(SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER); + for (AuraEffect const* aurEff : critChanceForCaster) + { + if (aurEff->GetCasterGUID() != GetGUID()) + continue; + + crit += aurEff->GetAmount(); + } + crit += victim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE); // reduce crit chance from Rating for players @@ -3188,6 +3188,15 @@ int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const return 0; } +bool Unit::CanMoveDuringChannel() const +{ + if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) + if (spell->getState() != SPELL_STATE_FINISHED) + return spell->GetSpellInfo()->HasAttribute(SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING) && spell->IsChannelActive(); + + return false; +} + bool Unit::isInFrontInMap(Unit const* target, float distance, float arc) const { return IsWithinDistInMap(target, distance) && HasInArc(arc, target); @@ -3748,6 +3757,77 @@ void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode) RemoveAura(aurApp, mode); } +void Unit::RemoveAppliedAuras(std::function<bool(AuraApplication const*)> const& check) +{ + for (AuraApplicationMap::iterator iter = m_appliedAuras.begin(); iter != m_appliedAuras.end();) + { + if (check(iter->second)) + { + RemoveAura(iter); + continue; + } + ++iter; + } +} + +void Unit::RemoveOwnedAuras(std::function<bool(Aura const*)> const& check) +{ + for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();) + { + if (check(iter->second)) + { + RemoveOwnedAura(iter); + continue; + } + ++iter; + } +} + +void Unit::RemoveAppliedAuras(uint32 spellId, std::function<bool(AuraApplication const*)> const& check) +{ + for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);) + { + if (check(iter->second)) + { + RemoveAura(iter); + continue; + } + ++iter; + } +} + +void Unit::RemoveOwnedAuras(uint32 spellId, std::function<bool(Aura const*)> const& check) +{ + for (AuraMap::iterator iter = m_ownedAuras.lower_bound(spellId); iter != m_ownedAuras.upper_bound(spellId);) + { + if (check(iter->second)) + { + RemoveOwnedAura(iter); + continue; + } + ++iter; + } +} + +void Unit::RemoveAurasByType(AuraType auraType, std::function<bool(AuraApplication const*)> const& check) +{ + for (AuraEffectList::iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) + { + Aura* aura = (*iter)->GetBase(); + AuraApplication * aurApp = aura->GetApplicationOfTarget(GetGUID()); + ASSERT(aurApp); + + ++iter; + if (check(aurApp)) + { + uint32 removedAuras = m_removedAurasCount; + RemoveAura(aurApp); + if (m_removedAurasCount > removedAuras + 1) + iter = m_modAuras[auraType].begin(); + } + } +} + void Unit::RemoveAurasDueToSpell(uint32 spellId, ObjectGuid casterGUID, uint8 reqEffMask, AuraRemoveMode removeMode) { for (AuraApplicationMap::iterator iter = m_appliedAuras.lower_bound(spellId); iter != m_appliedAuras.upper_bound(spellId);) @@ -4113,6 +4193,16 @@ void Unit::RemoveArenaAuras() } } +void Unit::RemoveAurasOnEvade() +{ + if (IsCharmedOwnedByPlayerOrPlayer()) // if it is a player owned creature it should not remove the aura + return; + + // don't remove vehicle auras, passengers aren't supposed to drop off the vehicle + // don't remove clone caster on evade (to be verified) + RemoveAllAurasExceptType(SPELL_AURA_CONTROL_VEHICLE, SPELL_AURA_CLONE_CASTER); +} + void Unit::RemoveAllAurasOnDeath() { // used just after dieing to remove all visible auras @@ -4355,13 +4445,10 @@ void Unit::GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelCharges if (aura->GetSpellInfo()->GetDispelMask() & dispelMask) { - if (aura->GetSpellInfo()->Dispel == DISPEL_MAGIC) - { - // do not remove positive auras if friendly target - // negative auras if non-friendly target - if (aurApp->IsPositive() == IsFriendlyTo(caster)) - continue; - } + // do not remove positive auras if friendly target + // negative auras if non-friendly target + if (aurApp->IsPositive() == IsFriendlyTo(caster)) + continue; // The charges / stack amounts don't count towards the total number of auras that can be dispelled. // Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell @@ -5208,7 +5295,7 @@ void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit* target, uint8 /*SwingType } //victim may be NULL -bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown) +bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, Milliseconds& cooldown) { SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo(); uint32 effIndex = triggeredByAura->GetEffIndex(); @@ -5218,8 +5305,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere ? ToPlayer()->GetItemByGuid(triggeredByAura->GetBase()->GetCastItemGUID()) : NULL; uint32 triggered_spell_id = 0; - uint32 cooldown_spell_id = 0; // for random trigger, will be one of the triggered spell to avoid repeatable triggers - // otherwise, it's the triggered_spell_id by default Unit* target = victim; int32 basepoints0 = 0; ObjectGuid originalCaster; @@ -5295,24 +5380,20 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere case CLASS_PALADIN: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 case CLASS_DRUID: // 39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409 triggered_spell_id = RAND(39511, 40997, 40998, 40999, 41002, 41005, 41009, 41011, 41409); - cooldown_spell_id = 39511; break; case CLASS_ROGUE: // 39511, 40997, 40998, 41002, 41005, 41011 case CLASS_WARRIOR: // 39511, 40997, 40998, 41002, 41005, 41011 case CLASS_DEATH_KNIGHT: triggered_spell_id = RAND(39511, 40997, 40998, 41002, 41005, 41011); - cooldown_spell_id = 39511; break; case CLASS_PRIEST: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_SHAMAN: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_MAGE: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 case CLASS_WARLOCK: // 40999, 41002, 41005, 41009, 41011, 41406, 41409 triggered_spell_id = RAND(40999, 41002, 41005, 41009, 41011, 41406, 41409); - cooldown_spell_id = 40999; break; case CLASS_HUNTER: // 40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409 triggered_spell_id = RAND(40997, 40999, 41002, 41005, 41009, 41011, 41406, 41409); - cooldown_spell_id = 40997; break; default: return false; @@ -5542,11 +5623,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere uint8 rand_spell = urand(0, (RandomSpells.size() - 1)); CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); - for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr) - { - if (!GetSpellHistory()->HasCooldown(*itr)) - GetSpellHistory()->AddCooldown(*itr, 0, std::chrono::seconds(cooldown)); - } break; } case 71562: // Deathbringer's Will Heroic @@ -5588,11 +5664,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere uint8 rand_spell = urand(0, (RandomSpells.size() - 1)); CastSpell(target, RandomSpells[rand_spell], true, castItem, triggeredByAura, originalCaster); - for (std::vector<uint32>::iterator itr = RandomSpells.begin(); itr != RandomSpells.end(); ++itr) - { - if (!GetSpellHistory()->HasCooldown(*itr)) - GetSpellHistory()->AddCooldown(*itr, 0, std::chrono::seconds(cooldown)); - } break; } case 65032: // Boom aura (321 Boombot) @@ -6230,24 +6301,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere return true; } } - // Eclipse - if (dummySpell->SpellIconID == 2856 && GetTypeId() == TYPEID_PLAYER) - { - if (!procSpell || effIndex != 0) - return false; - - bool isWrathSpell = (procSpell->SpellFamilyFlags[0] & 1); - - if (!roll_chance_f(dummySpell->ProcChance * (isWrathSpell ? 0.6f : 1.0f))) - return false; - - target = this; - if (target->HasAura(isWrathSpell ? 48517 : 48518)) - return false; - - triggered_spell_id = isWrathSpell ? 48518 : 48517; - break; - } break; } case SPELLFAMILY_ROGUE: @@ -6412,6 +6465,8 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere // 4 healing tick basepoints0 = triggerAmount * damage / 400; triggered_spell_id = 54203; + // Add remaining ticks to healing done + basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), triggered_spell_id, SPELL_AURA_PERIODIC_HEAL); break; } switch (dummySpell->Id) @@ -6428,7 +6483,7 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere // Item - Paladin T8 Holy 4P Bonus if (Unit* caster = triggeredByAura->GetCaster()) if (AuraEffect const* aurEff = caster->GetAuraEffect(64895, 0)) - cooldown = aurEff->GetAmount(); + cooldown = Milliseconds(aurEff->GetAmount()); target = this; break; @@ -6743,10 +6798,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere if (!player || !castItem || !castItem->IsEquipped() || !victim || !victim->IsAlive()) return false; - // custom cooldown processing case - if (cooldown && GetSpellHistory()->HasCooldown(dummySpell->Id)) - return false; - if (triggeredByAura->GetBase() && castItem->GetGUID() != triggeredByAura->GetBase()->GetCastItemGUID()) return false; @@ -6809,8 +6860,8 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere triggered_spell_id = 33750; // apply cooldown before cast to prevent processing itself - if (cooldown) - player->GetSpellHistory()->AddCooldown(dummySpell->Id, 0, std::chrono::seconds(cooldown)); + triggeredByAura->GetBase()->AddProcCooldown(std::chrono::steady_clock::now() + cooldown); + cooldown = Milliseconds::zero(); // Attack Twice for (uint32 i = 0; i < 2; ++i) @@ -7053,10 +7104,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere if (!procSpell || GetTypeId() != TYPEID_PLAYER || !victim) return false; - // custom cooldown processing case - if (cooldown && GetTypeId() == TYPEID_PLAYER && GetSpellHistory()->HasCooldown(dummySpell->Id)) - return false; - uint32 spellId = 0; // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost switch (procSpell->Id) @@ -7102,10 +7149,6 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere } CastSpell(victim, spellId, true, castItem, triggeredByAura); - - if (cooldown && GetTypeId() == TYPEID_PLAYER) - GetSpellHistory()->AddCooldown(dummySpell->Id, 0, std::chrono::seconds(cooldown)); - return true; } // Static Shock @@ -7407,26 +7450,17 @@ bool Unit::HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggere return false; } - if (cooldown_spell_id == 0) - cooldown_spell_id = triggered_spell_id; - - if (cooldown && GetTypeId() == TYPEID_PLAYER && GetSpellHistory()->HasCooldown(cooldown_spell_id)) - return false; - if (basepoints0) CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura, originalCaster); else CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura, originalCaster); - if (cooldown && GetTypeId() == TYPEID_PLAYER) - GetSpellHistory()->AddCooldown(cooldown_spell_id, 0, std::chrono::seconds(cooldown)); - return true; } // Used in case when access to whole aura is needed // All procs should be handled like this... -bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 cooldown, bool * handled) +bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 /*procFlag*/, uint32 procEx, bool* handled) { SpellInfo const* dummySpell = triggeredByAura->GetSpellInfo(); @@ -7638,12 +7672,6 @@ bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, Sp case 49222: { *handled = true; - if (cooldown && GetTypeId() == TYPEID_PLAYER) - { - if (GetSpellHistory()->HasCooldown(100000)) - return false; - GetSpellHistory()->AddCooldown(100000, 0, std::chrono::seconds(cooldown)); - } return true; } // Hungering Cold aura drop @@ -7686,7 +7714,7 @@ bool Unit::HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, Sp return false; } -bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown) +bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx) { // Get triggered aura spell info SpellInfo const* auraSpellInfo = triggeredByAura->GetSpellInfo(); @@ -7712,91 +7740,6 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg { switch (auraSpellInfo->SpellFamilyName) { - case SPELLFAMILY_GENERIC: - switch (auraSpellInfo->Id) - { - case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket) - // Pct value stored in dummy - basepoints0 = victim->GetCreateHealth() * auraSpellInfo->Effects[1].CalcValue() / 100; - target = victim; - break; - case 57345: // Darkmoon Card: Greatness - { - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); } - // intellect - if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);} - // spirit - if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; } - break; - } - case 64568: // Blood Reserve - { - if (HealthBelowPctDamaged(35, damage)) - { - CastCustomSpell(this, 64569, &triggerAmount, NULL, NULL, true); - RemoveAura(64568); - } - return false; - } - case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket - { - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; } - break; - } - case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket - { - float stat = 0.0f; - // strength - if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); } - // agility - if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; } - break; - } - // Mana Drain Trigger - case 27522: - case 40336: - { - // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target. - if (IsAlive()) - CastSpell(this, 29471, true, castItem, triggeredByAura); - if (victim && victim->IsAlive()) - CastSpell(victim, 27526, true, castItem, triggeredByAura); - return true; - } - // Evasive Maneuvers - case 50240: - { - // Remove a Evasive Charge - Aura* charge = GetAura(50241); - if (charge && charge->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL)) - RemoveAurasDueToSpell(50240); - break; - } - } - break; - case SPELLFAMILY_MAGE: - if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed - { - switch (auraSpellInfo->Id) - { - case 31641: // Rank 1 - case 31642: // Rank 2 - trigger_spell_id = 31643; - break; - default: - TC_LOG_ERROR("entities.unit", "Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed", auraSpellInfo->Id); - return false; - } - } - break; case SPELLFAMILY_WARLOCK: { // Drain Soul @@ -7819,325 +7762,6 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura return false; } - // Nether Protection - else if (auraSpellInfo->SpellIconID == 1985) - { - if (!procSpell) - return false; - switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) - { - case SPELL_SCHOOL_NORMAL: - return false; // ignore - case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break; - case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break; - case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break; - case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break; - case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break; - case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break; - default: - return false; - } - } - break; - } - case SPELLFAMILY_PRIEST: - { - // Blessed Recovery - if (auraSpellInfo->SpellIconID == 1875) - { - switch (auraSpellInfo->Id) - { - case 27811: trigger_spell_id = 27813; break; - case 27815: trigger_spell_id = 27817; break; - case 27816: trigger_spell_id = 27818; break; - default: - TC_LOG_ERROR("entities.unit", "Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id); - return false; - } - basepoints0 = CalculatePct(int32(damage), triggerAmount) / 3; - target = this; - // Add remaining ticks to healing done - basepoints0 += GetRemainingPeriodicAmount(GetGUID(), trigger_spell_id, SPELL_AURA_PERIODIC_HEAL); - } - break; - } - case SPELLFAMILY_DRUID: - { - switch (auraSpellInfo->Id) - { - // Druid Forms Trinket - case 37336: - { - switch (GetShapeshiftForm()) - { - case FORM_NONE: trigger_spell_id = 37344; break; - case FORM_CAT: trigger_spell_id = 37341; break; - case FORM_BEAR: - case FORM_DIREBEAR: trigger_spell_id = 37340; break; - case FORM_TREE: trigger_spell_id = 37342; break; - case FORM_MOONKIN: trigger_spell_id = 37343; break; - default: - return false; - } - break; - } - // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) - case 67353: - { - switch (GetShapeshiftForm()) - { - case FORM_CAT: trigger_spell_id = 67355; break; - case FORM_BEAR: - case FORM_DIREBEAR: trigger_spell_id = 67354; break; - default: - return false; - } - break; - } - default: - break; - } - break; - } - case SPELLFAMILY_HUNTER: - { - if (auraSpellInfo->SpellIconID == 3247) // Piercing Shots - { - switch (auraSpellInfo->Id) - { - case 53234: // Rank 1 - case 53237: // Rank 2 - case 53238: // Rank 3 - trigger_spell_id = 63468; - break; - default: - TC_LOG_ERROR("entities.unit", "Unit::HandleProcTriggerSpell: Spell %u miss posibly Piercing Shots", auraSpellInfo->Id); - return false; - } - SpellInfo const* TriggerPS = sSpellMgr->GetSpellInfo(trigger_spell_id); - if (!TriggerPS) - return false; - - basepoints0 = CalculatePct(int32(damage), triggerAmount) / (TriggerPS->GetMaxDuration() / TriggerPS->Effects[0].Amplitude); - basepoints0 += victim->GetRemainingPeriodicAmount(GetGUID(), trigger_spell_id, SPELL_AURA_PERIODIC_DAMAGE); - break; - } - // Item - Hunter T9 4P Bonus - if (auraSpellInfo->Id == 67151) - { - trigger_spell_id = 68130; - target = this; - break; - } - break; - } - case SPELLFAMILY_PALADIN: - { - switch (auraSpellInfo->Id) - { - // Soul Preserver - case 60510: - { - switch (getClass()) - { - case CLASS_DRUID: - trigger_spell_id = 60512; - break; - case CLASS_PALADIN: - trigger_spell_id = 60513; - break; - case CLASS_PRIEST: - trigger_spell_id = 60514; - break; - case CLASS_SHAMAN: - trigger_spell_id = 60515; - break; - } - - target = this; - break; - } - case 37657: // Lightning Capacitor - case 54841: // Thunder Capacitor - case 67712: // Item - Coliseum 25 Normal Caster Trinket - case 67758: // Item - Coliseum 25 Heroic Caster Trinket - { - if (!victim || !victim->IsAlive() || GetTypeId() != TYPEID_PLAYER) - return false; - - uint32 stack_spell_id = 0; - switch (auraSpellInfo->Id) - { - case 37657: - stack_spell_id = 37658; - trigger_spell_id = 37661; - break; - case 54841: - stack_spell_id = 54842; - trigger_spell_id = 54843; - break; - case 67712: - stack_spell_id = 67713; - trigger_spell_id = 67714; - break; - case 67758: - stack_spell_id = 67759; - trigger_spell_id = 67760; - break; - } - - CastSpell(this, stack_spell_id, true, NULL, triggeredByAura); - - Aura* dummy = GetAura(stack_spell_id); - if (!dummy || dummy->GetStackAmount() < triggerAmount) - return false; - - RemoveAurasDueToSpell(stack_spell_id); - target = victim; - break; - } - default: - // Illumination - if (auraSpellInfo->SpellIconID == 241) - { - if (!procSpell) - return false; - // procspell is triggered spell but we need mana cost of original cast spell - uint32 originalSpellId = procSpell->Id; - // Holy Shock heal - if (procSpell->SpellFamilyFlags[1] & 0x00010000) - { - switch (procSpell->Id) - { - case 25914: originalSpellId = 20473; break; - case 25913: originalSpellId = 20929; break; - case 25903: originalSpellId = 20930; break; - case 27175: originalSpellId = 27174; break; - case 33074: originalSpellId = 33072; break; - case 48820: originalSpellId = 48824; break; - case 48821: originalSpellId = 48825; break; - default: - TC_LOG_ERROR("entities.unit", "Unit::HandleProcTriggerSpell: Spell %u not handled in HShock", procSpell->Id); - return false; - } - } - SpellInfo const* originalSpell = sSpellMgr->GetSpellInfo(originalSpellId); - if (!originalSpell) - { - TC_LOG_ERROR("entities.unit", "Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu", originalSpellId); - return false; - } - // percent stored in effect 1 (class scripts) base points - int32 cost = int32(originalSpell->ManaCost + CalculatePct(GetCreateMana(), originalSpell->ManaCostPercentage)); - basepoints0 = CalculatePct(cost, auraSpellInfo->Effects[1].CalcValue()); - trigger_spell_id = 20272; - target = this; - } - break; - } - break; - } - case SPELLFAMILY_SHAMAN: - { - switch (auraSpellInfo->Id) - { - case 30881: // Nature's Guardian Rank 1 - case 30883: // Nature's Guardian Rank 2 - case 30884: // Nature's Guardian Rank 3 - case 30885: // Nature's Guardian Rank 4 - case 30886: // Nature's Guardian Rank 5 - { - if (HealthBelowPct(30)) - { - basepoints0 = int32(auraSpellInfo->Effects[EFFECT_0].CalcValue() * GetMaxHealth() / 100.0f); - target = this; - trigger_spell_id = 31616; - /// @todo Threat part - } - else - return false; - break; - } - default: - { - // Lightning Shield (overwrite non existing triggered spell call in spell.dbc - if (auraSpellInfo->SpellFamilyFlags[0] & 0x400) - { - trigger_spell_id = sSpellMgr->GetSpellWithRank(26364, auraSpellInfo->GetRank()); - } - // Nature's Guardian - else if (auraSpellInfo->SpellIconID == 2013) - { - // Check health condition - should drop to less 30% (damage deal after this!) - if (!HealthBelowPctDamaged(30, damage)) - return false; - - if (victim && victim->IsAlive()) - victim->getThreatManager().modifyThreatPercent(this, -10); - - basepoints0 = int32(CountPctFromMaxHealth(triggerAmount)); - trigger_spell_id = 31616; - target = this; - } - } - } - break; - } - case SPELLFAMILY_DEATHKNIGHT: - { - // Acclimation - if (auraSpellInfo->SpellIconID == 1930) - { - if (!procSpell) - return false; - switch (GetFirstSchoolInMask(procSpell->GetSchoolMask())) - { - case SPELL_SCHOOL_NORMAL: - return false; // ignore - case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break; - case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break; - case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break; - case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break; - case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break; - case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break; - default: - return false; - } - } - // Blood Presence (Improved) - else if (auraSpellInfo->Id == 63611) - { - if (GetTypeId() != TYPEID_PLAYER) - return false; - - trigger_spell_id = 50475; - basepoints0 = CalculatePct(int32(damage), triggerAmount); - } - // Item - Death Knight T10 Melee 4P Bonus - else if (auraSpellInfo->Id == 70656) - { - if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT) - return false; - - for (uint8 i = 0; i < MAX_RUNES; ++i) - if (ToPlayer()->GetRuneCooldown(i) == 0) - return false; - } - break; - } - case SPELLFAMILY_ROGUE: - { - switch (auraSpellInfo->Id) - { - // Rogue T10 2P bonus, should only proc on caster - case 70805: - { - if (victim != this) - return false; - break; - } - } - break; } default: break; @@ -8171,7 +7795,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg float averageDmg = 0; // now compute approximate weapon damage by formula from wowwiki.com - if (procFlags & PROC_FLAG_DONE_OFFHAND_ATTACK) + if (procFlag & PROC_FLAG_DONE_OFFHAND_ATTACK) averageDmg = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE)) / 2.f; else averageDmg = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE)) / 2.f; @@ -8248,7 +7872,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 53232: { // This effect only from Rapid Fire (ability cast) - if (!(procSpell->SpellFamilyFlags[0] & 0x20)) + if (!procSpell || !(procSpell->SpellFamilyFlags[0] & 0x20)) return false; break; } @@ -8266,7 +7890,9 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 15337: // Improved Spirit Tap (Rank 1) case 15338: // Improved Spirit Tap (Rank 2) { - ASSERT(procSpell); + if (!procSpell) + return false; + if (procSpell->SpellFamilyFlags[0] & 0x800000) if ((procSpell->Id != 58381) || !roll_chance_i(50)) return false; @@ -8333,13 +7959,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg if (!target) return false; - if (cooldown && target->GetTypeId() == TYPEID_PLAYER && target->GetSpellHistory()->HasCooldown(trigger_spell_id)) - return false; - target->CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura); - - if (cooldown && GetTypeId() == TYPEID_PLAYER) - GetSpellHistory()->AddCooldown(trigger_spell_id, 0, std::chrono::seconds(cooldown)); return true; } // Cast positive spell on enemy target @@ -8448,7 +8068,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg // Astral Shift case 52179: { - if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim) + if (!procSpell || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == victim) return false; // Need stun, fear or silence mechanic @@ -8470,7 +8090,7 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 56453: { // Proc only from Frost/Freezing trap activation or from Freezing Arrow (the periodic dmg proc handled elsewhere) - if (!(procFlags & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount)) + if (!(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount)) return false; break; } @@ -8500,13 +8120,15 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg case 65081: { // Proc only from PW:S cast - if (!(procSpell->SpellFamilyFlags[0] & 0x00000001)) + if (!procSpell || !(procSpell->SpellFamilyFlags[0] & 0x00000001)) return false; break; } // Culling the Herd case 70893: { + if (!procSpell) + return false; // check if we're doing a critical hit if (!(procSpell->SpellFamilyFlags[1] & 0x10000000) && (procEx != PROC_EX_CRITICAL_HIT)) return false; @@ -8517,29 +8139,23 @@ bool Unit::HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* trigg } } - if (cooldown && GetTypeId() == TYPEID_PLAYER && GetSpellHistory()->HasCooldown(trigger_spell_id)) - return false; - // extra attack should hit same target if (triggerEntry->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS)) target = victim; // try detect target manually if not set if (target == NULL) - target = !(procFlags & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && triggerEntry->IsPositive() ? this : victim; + target = !(procFlag & (PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS | PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS)) && triggerEntry->IsPositive() ? this : victim; if (basepoints0) CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); else CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura); - if (cooldown && GetTypeId() == TYPEID_PLAYER) - GetSpellHistory()->AddCooldown(trigger_spell_id, 0, std::chrono::seconds(cooldown)); - return true; } -bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 cooldown) +bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, AuraEffect* triggeredByAura, SpellInfo const* procSpell) { int32 scriptId = triggeredByAura->GetMiscValue(); @@ -8630,14 +8246,7 @@ bool Unit::HandleOverrideClassScriptAuraProc(Unit* victim, uint32 /*damage*/, Au return false; } - if (cooldown && GetTypeId() == TYPEID_PLAYER && GetSpellHistory()->HasCooldown(triggered_spell_id)) - return false; - CastSpell(victim, triggered_spell_id, true, castItem, triggeredByAura); - - if (cooldown && GetTypeId() == TYPEID_PLAYER) - GetSpellHistory()->AddCooldown(triggered_spell_id, 0, std::chrono::seconds(cooldown)); - return true; } @@ -8646,7 +8255,7 @@ void Unit::setPowerType(Powers new_powertype) if (getPowerType() == new_powertype) return; - SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE, new_powertype); if (GetTypeId() == TYPEID_PLAYER) { @@ -8921,7 +8530,7 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) } else { - if (victim->ToCreature()->IsInEvadeMode()) + if (victim->ToCreature()->IsEvadingAttacks()) return false; } @@ -8983,13 +8592,16 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) if (GetTypeId() == TYPEID_UNIT && !IsPet()) { // should not let player enter combat by right clicking target - doesn't helps + AddThreat(victim, 0.0f); SetInCombatWith(victim); if (victim->GetTypeId() == TYPEID_PLAYER) victim->SetInCombatWith(this); - AddThreat(victim, 0.0f); ToCreature()->SendAIReaction(AI_REACTION_HOSTILE); ToCreature()->CallAssistance(); + + // Remove emote state - will be restored on creature reset + SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); } // delay offhand weapon attack to next attack time @@ -9037,7 +8649,7 @@ bool Unit::AttackStop() if (creature->HasSearchedAssistance()) { creature->SetNoSearchAssistance(false); - UpdateSpeed(MOVE_RUN, false); + UpdateSpeed(MOVE_RUN); } } @@ -9230,7 +8842,7 @@ Unit* Unit::GetCharmer() const if (ObjectGuid charmerGUID = GetCharmerGUID()) return ObjectAccessor::GetUnit(*this, charmerGUID); - return NULL; + return nullptr; } Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const @@ -9371,7 +8983,7 @@ void Unit::SetMinion(Minion *minion, bool apply) // FIXME: hack, speed must be set only at follow if (GetTypeId() == TYPEID_PLAYER && minion->IsPet()) for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) - minion->SetSpeed(UnitMoveType(i), m_speed_rate[i], true); + minion->SetSpeedRate(UnitMoveType(i), m_speed_rate[i]); // Ghoul pets have energy instead of mana (is anywhere better place for this code?) if (minion->IsPetGhoul() || minion->IsRisenAlly()) @@ -10656,6 +10268,19 @@ float Unit::GetUnitSpellCriticalChance(Unit* victim, SpellInfo const* spellProto if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance); + // for this types the bonus was already added in GetUnitCriticalChance, do not add twice + if (spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE && spellProto->DmgClass != SPELL_DAMAGE_CLASS_RANGED) + { + AuraEffectList const& critChanceForCaster = victim->GetAuraEffectsByType(SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER); + for (AuraEffect const* aurEff : critChanceForCaster) + { + if (aurEff->GetCasterGUID() != GetGUID() || !aurEff->IsAffectedOnSpell(spellProto)) + continue; + + crit_chance += aurEff->GetAmount(); + } + } + return crit_chance > 0.0f ? crit_chance : 0.0f; } @@ -11791,22 +11416,20 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy) if (enemy) { if (IsAIEnabled) - { creature->AI()->EnterCombat(enemy); - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); // unit has engaged in combat, remove immunity so players can fight back - } + if (creature->GetFormation()) creature->GetFormation()->MemberAttackStart(creature, enemy); } if (IsPet()) { - UpdateSpeed(MOVE_RUN, true); - UpdateSpeed(MOVE_SWIM, true); - UpdateSpeed(MOVE_FLIGHT, true); + UpdateSpeed(MOVE_RUN); + UpdateSpeed(MOVE_SWIM); + UpdateSpeed(MOVE_FLIGHT); } - if (!(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_MOUNTED_COMBAT)) + if (!(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_MOUNTED_COMBAT_ALLOWED)) Dismount(); } @@ -11835,9 +11458,6 @@ void Unit::ClearInCombat() // Player's state will be cleared in Player::UpdateContestedPvP if (Creature* creature = ToCreature()) { - if (creature->GetCreatureTemplate() && creature->GetCreatureTemplate()->unit_flags & UNIT_FLAG_IMMUNE_TO_PC) - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); // set immunity state to the one from db on evade - ClearUnitState(UNIT_STATE_ATTACK_PLAYER); if (HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED)) SetUInt32Value(UNIT_DYNAMIC_FLAGS, creature->GetCreatureTemplate()->dynamicflags); @@ -11847,7 +11467,7 @@ void Unit::ClearInCombat() if (Unit* owner = GetOwner()) for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) if (owner->GetSpeedRate(UnitMoveType(i)) > GetSpeedRate(UnitMoveType(i))) - SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true); + SetSpeedRate(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i))); } else if (!IsCharmed()) return; @@ -11856,6 +11476,7 @@ void Unit::ClearInCombat() ToPlayer()->UpdatePotionCooldown(); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LEAVE_COMBAT); } bool Unit::isTargetableForAttack(bool checkFakeDeath) const @@ -11864,7 +11485,7 @@ bool Unit::isTargetableForAttack(bool checkFakeDeath) const return false; if (HasFlag(UNIT_FIELD_FLAGS, - UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC)) + UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) return false; if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->IsGameMaster()) @@ -11934,35 +11555,33 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo || target->GetReactionTo(this) > REP_NEUTRAL) return false; + Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : nullptr; + Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : nullptr; + // Not all neutral creatures can be attacked (even some unfriendly faction does not react aggresive to you, like Sporaggar) - if (GetReactionTo(target) == REP_NEUTRAL && - target->GetReactionTo(this) <= REP_NEUTRAL) + if ( + (playerAffectingAttacker && !playerAffectingTarget) || + (!playerAffectingAttacker && playerAffectingTarget) + ) { - if (!(target->GetTypeId() == TYPEID_PLAYER && GetTypeId() == TYPEID_PLAYER) && - !(target->GetTypeId() == TYPEID_UNIT && GetTypeId() == TYPEID_UNIT)) - { - Player const* player = target->GetTypeId() == TYPEID_PLAYER ? target->ToPlayer() : ToPlayer(); - Unit const* creature = target->GetTypeId() == TYPEID_UNIT ? target : this; + Player const* player = playerAffectingAttacker ? playerAffectingAttacker : playerAffectingTarget; + Unit const* creature = playerAffectingAttacker ? target : this; - if (FactionTemplateEntry const* factionTemplate = creature->GetFactionTemplateEntry()) - { - if (!(player->GetReputationMgr().GetForcedRankIfAny(factionTemplate))) - if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction)) - if (FactionState const* repState = player->GetReputationMgr().GetState(factionEntry)) - if (!(repState->Flags & FACTION_FLAG_AT_WAR)) - return false; + if (FactionTemplateEntry const* factionTemplate = creature->GetFactionTemplateEntry()) + { + if (!(player->GetReputationMgr().GetForcedRankIfAny(factionTemplate))) + if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction)) + if (FactionState const* repState = player->GetReputationMgr().GetState(factionEntry)) + if (!(repState->Flags & FACTION_FLAG_AT_WAR)) + return false; - } } } Creature const* creatureAttacker = ToCreature(); - if (creatureAttacker && creatureAttacker->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER) + if (creatureAttacker && creatureAttacker->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) return false; - Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL; - Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL; - // check duel - before sanctuary checks if (playerAffectingAttacker && playerAffectingTarget) if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0) @@ -12044,11 +11663,14 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co // can't assist non-friendly targets if (GetReactionTo(target) < REP_NEUTRAL && target->GetReactionTo(this) < REP_NEUTRAL - && (!ToCreature() || !(ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER))) + && (!ToCreature() || !(ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT))) return false; + // Controlled player case, we can assist creatures (reaction already checked above, our faction == charmer faction) + if (GetTypeId() == TYPEID_PLAYER && IsCharmed() && GetCharmerGUID().IsCreature()) + return true; // PvP case - if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) + else if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) { Player const* targetPlayerOwner = target->GetAffectingPlayer(); if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) @@ -12078,7 +11700,7 @@ bool Unit::_IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) co && !((target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_PVP))) { if (Creature const* creatureTarget = target->ToCreature()) - return creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER || creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_AID_PLAYERS; + return creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT || creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_ASSIST; } return true; } @@ -12233,7 +11855,7 @@ void Unit::SetVisible(bool x) UpdateObjectVisibility(); } -void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) +void Unit::UpdateSpeed(UnitMoveType mtype) { int32 main_speed_mod = 0; float stack_bonus = 1.0f; @@ -12296,7 +11918,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) // Update speed for vehicle if available if (GetTypeId() == TYPEID_PLAYER && GetVehicle()) - GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT, true); + GetVehicleBase()->UpdateSpeed(MOVE_FLIGHT); break; } default: @@ -12344,7 +11966,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) if (Creature* creature = ToCreature()) { uint32 immuneMask = creature->GetCreatureTemplate()->MechanicImmuneMask; - if (immuneMask & (1 << MECHANIC_SNARE) || immuneMask & (1 << MECHANIC_DAZE)) + if (immuneMask & (1 << (MECHANIC_SNARE - 1)) || immuneMask & (1 << (MECHANIC_DAZE - 1))) break; } @@ -12378,7 +12000,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) speed = min_speed; } - SetSpeed(mtype, speed, forced); + SetSpeedRate(mtype, speed); } float Unit::GetSpeed(UnitMoveType mtype) const @@ -12386,7 +12008,12 @@ float Unit::GetSpeed(UnitMoveType mtype) const return m_speed_rate[mtype]*(IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype]); } -void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced) +void Unit::SetSpeed(UnitMoveType mtype, float newValue) +{ + SetSpeedRate(mtype, newValue / (IsControlledByPlayer() ? playerBaseMoveSpeed[mtype] : baseMoveSpeed[mtype])); +} + +void Unit::SetSpeedRate(UnitMoveType mtype, float rate) { if (rate < 0) rate = 0.0f; @@ -12399,102 +12026,67 @@ void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced) propagateSpeedChange(); - WorldPacket data; - if (!forced) + // Spline packets are for units controlled by AI. "Force speed change" (wrongly named opcodes) and "move set speed" packets are for units controlled by a player. + static Opcodes const moveTypeToOpcode[MAX_MOVE_TYPE][3] = + { + {SMSG_SPLINE_SET_WALK_SPEED, SMSG_FORCE_WALK_SPEED_CHANGE, MSG_MOVE_SET_WALK_SPEED }, + {SMSG_SPLINE_SET_RUN_SPEED, SMSG_FORCE_RUN_SPEED_CHANGE, MSG_MOVE_SET_RUN_SPEED }, + {SMSG_SPLINE_SET_RUN_BACK_SPEED, SMSG_FORCE_RUN_BACK_SPEED_CHANGE, MSG_MOVE_SET_RUN_BACK_SPEED }, + {SMSG_SPLINE_SET_SWIM_SPEED, SMSG_FORCE_SWIM_SPEED_CHANGE, MSG_MOVE_SET_SWIM_SPEED }, + {SMSG_SPLINE_SET_SWIM_BACK_SPEED, SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, MSG_MOVE_SET_SWIM_BACK_SPEED }, + {SMSG_SPLINE_SET_TURN_RATE, SMSG_FORCE_TURN_RATE_CHANGE, MSG_MOVE_SET_TURN_RATE }, + {SMSG_SPLINE_SET_FLIGHT_SPEED, SMSG_FORCE_FLIGHT_SPEED_CHANGE, MSG_MOVE_SET_FLIGHT_SPEED }, + {SMSG_SPLINE_SET_FLIGHT_BACK_SPEED, SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, MSG_MOVE_SET_FLIGHT_BACK_SPEED }, + {SMSG_SPLINE_SET_PITCH_RATE, SMSG_FORCE_PITCH_RATE_CHANGE, MSG_MOVE_SET_PITCH_RATE }, + }; + + if (GetTypeId() == TYPEID_PLAYER) { - switch (mtype) - { - case MOVE_WALK: - data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_RUN: - data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_RUN_BACK: - data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_SWIM: - data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_SWIM_BACK: - data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_TURN_RATE: - data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_FLIGHT: - data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_FLIGHT_BACK: - data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4); - break; - case MOVE_PITCH_RATE: - data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4); - break; - default: - TC_LOG_ERROR("entities.unit", "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype); - return; - } + // register forced speed changes for WorldSession::HandleForceSpeedChangeAck + // and do it only for real sent packets and use run for run/mounted as client expected + ++ToPlayer()->m_forced_speed_changes[mtype]; + + if (!IsInCombat()) + if (Pet* pet = ToPlayer()->GetPet()) + pet->SetSpeedRate(mtype, m_speed_rate[mtype]); + } + + if (Player* playerMover = GetPlayerMover()) // unit controlled by a player. + { + // Send notification to self. this packet is only sent to one client (the client of the player concerned by the change). + WorldPacket self; + self.Initialize(moveTypeToOpcode[mtype][1], mtype != MOVE_RUN ? 8 + 4 + 4 : 8 + 4 + 1 + 4); + self << GetPackGUID(); + self << (uint32)0; // Movement counter. Unimplemented at the moment! NUM_PMOVE_EVTS = 0x39Z. + if (mtype == MOVE_RUN) + self << uint8(1); // unknown byte added in 2.1.0 + self << float(GetSpeed(mtype)); + playerMover->GetSession()->SendPacket(&self); + // Send notification to other players. sent to every clients (if in range) except one: the client of the player concerned by the change. + WorldPacket data; + data.Initialize(moveTypeToOpcode[mtype][2], 8 + 30 + 4); + data << GetPackGUID(); BuildMovementPacket(&data); data << float(GetSpeed(mtype)); - SendMessageToSet(&data, true); + playerMover->SendMessageToSet(&data, false); } - else + else // unit controlled by AI. { - if (GetTypeId() == TYPEID_PLAYER) - { - // register forced speed changes for WorldSession::HandleForceSpeedChangeAck - // and do it only for real sent packets and use run for run/mounted as client expected - ++ToPlayer()->m_forced_speed_changes[mtype]; - - if (!IsInCombat()) - if (Pet* pet = ToPlayer()->GetPet()) - pet->SetSpeed(mtype, m_speed_rate[mtype], forced); - } - - switch (mtype) - { - case MOVE_WALK: - data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16); - break; - case MOVE_RUN: - data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17); - break; - case MOVE_RUN_BACK: - data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16); - break; - case MOVE_SWIM: - data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16); - break; - case MOVE_SWIM_BACK: - data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16); - break; - case MOVE_TURN_RATE: - data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16); - break; - case MOVE_FLIGHT: - data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16); - break; - case MOVE_FLIGHT_BACK: - data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16); - break; - case MOVE_PITCH_RATE: - data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16); - break; - default: - TC_LOG_ERROR("entities.unit", "Unit::SetSpeed: Unsupported move type (%d), data not sent to client.", mtype); - return; - } + // send notification to every clients. + WorldPacket data; + data.Initialize(moveTypeToOpcode[mtype][0], 8 + 4); data << GetPackGUID(); - data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39 - if (mtype == MOVE_RUN) - data << uint8(0); // new 2.1.0 data << float(GetSpeed(mtype)); - SendMessageToSet(&data, true); + SendMessageToSet(&data, false); } } +bool Unit::IsGhouled() const +{ + return HasAura(SPELL_DK_RAISE_ALLY); +} + void Unit::setDeathState(DeathState s) { // Death state needs to be updated before RemoveAllAurasOnDeath() is called, to prevent entering combat @@ -12597,7 +12189,7 @@ float Unit::ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask) void Unit::AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask, SpellInfo const* threatSpell) { // Only mobs can manage threat lists - if (CanHaveThreatList()) + if (CanHaveThreatList() && !HasUnitState(UNIT_STATE_EVADE)) m_ThreatManager.addThreat(victim, fThreat, schoolMask, threatSpell); } @@ -12752,7 +12344,7 @@ Unit* Creature::SelectVictim() if (target && _IsTargetAcceptable(target) && CanCreatureAttack(target)) { - if(!IsFocusing()) + if (!IsFocusing()) SetInFront(target); return target; } @@ -13655,28 +13247,80 @@ void Unit::CleanupsBeforeDelete(bool finalCleanup) void Unit::UpdateCharmAI() { - if (GetTypeId() == TYPEID_PLAYER) - return; - - if (i_disabledAI) // disabled AI must be primary AI - { - if (!IsCharmed()) - { - delete i_AI; - i_AI = i_disabledAI; - i_disabledAI = NULL; - } - } - else + switch (GetTypeId()) { - if (IsCharmed()) + case TYPEID_UNIT: + if (i_disabledAI) // disabled AI must be primary AI + { + if (!IsCharmed()) + { + delete i_AI; + i_AI = i_disabledAI; + i_disabledAI = nullptr; + + if (GetTypeId() == TYPEID_UNIT) + ToCreature()->AI()->OnCharmed(false); + } + } + else + { + if (IsCharmed()) + { + i_disabledAI = i_AI; + if (isPossessed() || IsVehicle()) + i_AI = new PossessedAI(ToCreature()); + else + i_AI = new PetAI(ToCreature()); + } + } + break; + case TYPEID_PLAYER: { - i_disabledAI = i_AI; - if (isPossessed() || IsVehicle()) - i_AI = new PossessedAI(ToCreature()); + if (IsCharmed()) // if we are currently being charmed, then we should apply charm AI + { + i_disabledAI = i_AI; + + UnitAI* newAI = nullptr; + // first, we check if the creature's own AI specifies an override playerai for its owned players + if (Unit* charmer = GetCharmer()) + { + if (Creature* creatureCharmer = charmer->ToCreature()) + { + if (PlayerAI* charmAI = creatureCharmer->IsAIEnabled ? creatureCharmer->AI()->GetAIForCharmedPlayer(ToPlayer()) : nullptr) + newAI = charmAI; + } + else + { + TC_LOG_ERROR("misc", "Attempt to assign charm AI to player %s who is charmed by non-creature %s.", GetGUID().ToString().c_str(), GetCharmerGUID().ToString().c_str()); + } + } + if (!newAI) // otherwise, we default to the generic one + newAI = new SimpleCharmedPlayerAI(ToPlayer()); + i_AI = newAI; + newAI->OnCharmed(true); + } else - i_AI = new PetAI(ToCreature()); + { + if (i_AI) + { + // we allow the charmed PlayerAI to clean up + i_AI->OnCharmed(false); + // then delete it + delete i_AI; + } + else + { + TC_LOG_ERROR("misc", "Attempt to remove charm AI from player %s who doesn't currently have charm AI.", GetGUID().ToString().c_str()); + } + // and restore our previous PlayerAI (if we had one) + i_AI = i_disabledAI; + i_disabledAI = nullptr; + // IsAIEnabled gets handled in the caller + } + break; } + default: + TC_LOG_ERROR("misc", "Attempt to update charm AI for unit %s, which is neither player nor creature.", GetGUID().ToString().c_str()); } } @@ -13764,7 +13408,7 @@ void CharmInfo::InitPossessCreateSpells() break; } - for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i = 0; i < MAX_CREATURE_SPELLS; ++i) { uint32 spellId = _unit->ToCreature()->m_spells[i]; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); @@ -13951,6 +13595,20 @@ void CharmInfo::SetSpellAutocast(SpellInfo const* spellInfo, bool state) } } +Unit* Unit::GetMover() const +{ + if (Player const* player = ToPlayer()) + return player->m_mover; + return nullptr; +} + +Player* Unit::GetPlayerMover() const +{ + if (Unit* mover = GetMover()) + return mover->ToPlayer(); + return nullptr; +} + bool Unit::isFrozen() const { return HasAuraState(AURA_STATE_FROZEN); @@ -14151,6 +13809,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u HealInfo healInfo = HealInfo(actor, actionTarget, damage, procSpell, procSpell ? SpellSchoolMask(procSpell->SchoolMask) : SPELL_SCHOOL_MASK_NORMAL); ProcEventInfo eventInfo = ProcEventInfo(actor, actionTarget, target, procFlag, 0, 0, procExtra, nullptr, &damageInfo, &healInfo); + std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); ProcTriggeredList procTriggered; // Fill procTriggered list for (AuraApplicationMap::const_iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr) @@ -14158,6 +13817,10 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u // Do not allow auras to proc from effect triggered by itself if (procAura && procAura->Id == itr->first) continue; + + if (itr->second->GetBase()->IsProcOnCooldown(now)) + continue; + ProcTriggeredData triggerData(itr->second->GetBase()); // Defensive procs are active on absorbs (so absorption effects are not a hindrance) bool active = damage || (procExtra & PROC_EX_BLOCK && isVictim); @@ -14182,6 +13845,10 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u if (!triggerData.aura->CallScriptCheckProcHandlers(itr->second, eventInfo)) continue; + bool procSuccess = RollProcResult(target, triggerData.aura, attType, isVictim, triggerData.spellProcEvent); + if (!procSuccess) + continue; + // Triggered spells not triggering additional spells bool triggered = !spellProto->HasAttribute(SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED) ? (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) : false; @@ -14234,10 +13901,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u bool prepare = i->aura->CallScriptPrepareProcHandlers(aurApp, eventInfo); - // For players set spell cooldown if need - uint32 cooldown = 0; - if (prepare && GetTypeId() == TYPEID_PLAYER && i->spellProcEvent && i->spellProcEvent->cooldown) - cooldown = i->spellProcEvent->cooldown; + Milliseconds cooldown = Milliseconds::zero(); + if (prepare && i->spellProcEvent && i->spellProcEvent->cooldown) + cooldown = Seconds(i->spellProcEvent->cooldown); // Note: must SetCantProc(false) before return if (spellInfo->HasAttribute(SPELL_ATTR3_DISABLE_PROC)) @@ -14246,9 +13912,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u bool handled = i->aura->CallScriptProcHandlers(aurApp, eventInfo); // "handled" is needed as long as proc can be handled in multiple places - if (!handled && HandleAuraProc(target, damage, i->aura, procSpell, procFlag, procExtra, cooldown, &handled)) + if (!handled && HandleAuraProc(target, damage, i->aura, procSpell, procFlag, procExtra, &handled)) { - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), Id); + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), Id); takeCharges = true; } @@ -14256,7 +13922,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u { for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { - if (!(i->effMask & (1<<effIndex))) + if (!(i->effMask & (1 << effIndex))) continue; AuraEffect* triggeredByAura = i->aura->GetEffect(effIndex); @@ -14273,9 +13939,10 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u { case SPELL_AURA_PROC_TRIGGER_SPELL: { - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", + spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); // Don`t drop charge or add cooldown for not started trigger - if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) + if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra)) takeCharges = true; break; } @@ -14292,7 +13959,8 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u case SPELL_AURA_MANA_SHIELD: case SPELL_AURA_DUMMY: { - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", + spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); if (HandleDummyAuraProc(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; @@ -14301,20 +13969,22 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u case SPELL_AURA_MOD_SPELL_CRIT_CHANCE: case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN: case SPELL_AURA_MOD_MELEE_HASTE: - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, isVictim ? "a victim's" : "an attacker's", triggeredByAura->GetId()); + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", + spellInfo->Id, isVictim ? "a victim's" : "an attacker's", triggeredByAura->GetId()); takeCharges = true; break; case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS: { - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); - if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell, cooldown)) + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", + spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); + if (HandleOverrideClassScriptAuraProc(target, damage, triggeredByAura, procSpell)) takeCharges = true; break; } case SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE: { TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", - (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); + (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); HandleAuraRaidProcFromChargeWithValue(triggeredByAura); takeCharges = true; @@ -14323,7 +13993,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u case SPELL_AURA_RAID_PROC_FROM_CHARGE: { TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)", - (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); + (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); HandleAuraRaidProcFromCharge(triggeredByAura); takeCharges = true; @@ -14331,9 +14001,10 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u } case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE: { - TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); + TC_LOG_DEBUG("spells", "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", + spellInfo->Id, (isVictim ? "a victim's" : "an attacker's"), triggeredByAura->GetId()); - if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) + if (HandleProcTriggerSpell(target, damage, triggeredByAura, procSpell, procFlag, procExtra)) takeCharges = true; break; } @@ -14418,6 +14089,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u } // for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) } // if (!handled) + if (prepare && takeCharges && cooldown != Milliseconds::zero()) + i->aura->AddProcCooldown(now + cooldown); + // Remove charge (aura can be removed by triggers) if (prepare && useCharges && takeCharges) { @@ -14446,6 +14120,8 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* target, uint32 procFlag, u void Unit::GetProcAurasTriggeredOnEvent(std::list<AuraApplication*>& aurasTriggeringProc, std::list<AuraApplication*>* procAuras, ProcEventInfo eventInfo) { + std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); + // use provided list of auras which can proc if (procAuras) { @@ -14453,9 +14129,9 @@ void Unit::GetProcAurasTriggeredOnEvent(std::list<AuraApplication*>& aurasTrigge { ASSERT((*itr)->GetTarget() == this); if (!(*itr)->GetRemoveMode()) - if ((*itr)->GetBase()->IsProcTriggeredOnEvent(*itr, eventInfo)) + if ((*itr)->GetBase()->IsProcTriggeredOnEvent(*itr, eventInfo, now)) { - (*itr)->GetBase()->PrepareProcToTrigger(*itr, eventInfo); + (*itr)->GetBase()->PrepareProcToTrigger(*itr, eventInfo, now); aurasTriggeringProc.push_back(*itr); } } @@ -14465,9 +14141,9 @@ void Unit::GetProcAurasTriggeredOnEvent(std::list<AuraApplication*>& aurasTrigge { for (AuraApplicationMap::iterator itr = GetAppliedAuras().begin(); itr!= GetAppliedAuras().end(); ++itr) { - if (itr->second->GetBase()->IsProcTriggeredOnEvent(itr->second, eventInfo)) + if (itr->second->GetBase()->IsProcTriggeredOnEvent(itr->second, eventInfo, now)) { - itr->second->GetBase()->PrepareProcToTrigger(itr->second, eventInfo); + itr->second->GetBase()->PrepareProcToTrigger(itr->second, eventInfo, now); aurasTriggeringProc.push_back(itr->second); } } @@ -14600,7 +14276,7 @@ void Unit::SendMovementFlagUpdate(bool self /* = false */) bool Unit::IsSitState() const { - uint8 s = getStandState(); + uint8 s = GetStandState(); return s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR || s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR || @@ -14609,7 +14285,7 @@ bool Unit::IsSitState() const bool Unit::IsStandState() const { - uint8 s = getStandState(); + uint8 s = GetStandState(); return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL; } @@ -14646,7 +14322,7 @@ void Unit::SetDisplayId(uint32 modelId) SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId); // Set Gender by modelId if (CreatureModelInfo const* minfo = sObjectMgr->GetCreatureModelInfo(modelId)) - SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, minfo->gender); } void Unit::RestoreDisplayId() @@ -15089,23 +14765,23 @@ bool Unit::InitTamedPet(Pet* pet, uint8 level, uint32 spell_id) return true; } -bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent) +bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent) { - SpellInfo const* spellProto = aura->GetSpellInfo(); + SpellInfo const* spellInfo = aura->GetSpellInfo(); // let the aura be handled by new proc system if it has new entry - if (sSpellMgr->GetSpellProcEntry(spellProto->Id)) + if (sSpellMgr->GetSpellProcEntry(spellInfo->Id)) return false; // Get proc Event Entry - spellProcEvent = sSpellMgr->GetSpellProcEvent(spellProto->Id); + spellProcEvent = sSpellMgr->GetSpellProcEvent(spellInfo->Id); // Get EventProcFlag uint32 EventProcFlag; if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags EventProcFlag = spellProcEvent->procFlags; else - EventProcFlag = spellProto->ProcFlags; // else get from spell proto + EventProcFlag = spellInfo->ProcFlags; // else get from spell proto // Continue if no trigger exist if (!EventProcFlag) return false; @@ -15113,12 +14789,12 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const // Additional checks for triggered spells (ignore trap casts) if (procExtra & PROC_EX_INTERNAL_TRIGGERED && !(procFlag & PROC_FLAG_DONE_TRAP_ACTIVATION)) { - if (!spellProto->HasAttribute(SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED)) + if (!spellInfo->HasAttribute(SPELL_ATTR3_CAN_PROC_WITH_TRIGGERED)) return false; } // Check spellProcEvent data requirements - if (!sSpellMgr->IsSpellProcEventCanTriggeredBy(spellProto, spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active)) + if (!sSpellMgr->IsSpellProcEventCanTriggeredBy(spellInfo, spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active)) return false; // In most cases req get honor or XP from kill if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER) @@ -15136,15 +14812,15 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const } // Aura added by spell can`t trigger from self (prevent drop charges/do triggers) // But except periodic and kill triggers (can triggered from self) - if (procSpell && procSpell->Id == spellProto->Id - && !(spellProto->ProcFlags&(PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL))) + if (procSpell && procSpell->Id == spellInfo->Id + && !(spellInfo->ProcFlags&(PROC_FLAG_TAKEN_PERIODIC | PROC_FLAG_KILL))) return false; // Check if current equipment allows aura to proc if (!isVictim && GetTypeId() == TYPEID_PLAYER) { Player* player = ToPlayer(); - if (spellProto->EquippedItemClass == ITEM_CLASS_WEAPON) + if (spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON) { Item* item = NULL; if (attType == BASE_ATTACK) @@ -15157,19 +14833,26 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const if (player->IsInFeralForm()) return false; - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetTemplate()->SubClass) & spellInfo->EquippedItemSubClassMask)) return false; } - else if (spellProto->EquippedItemClass == ITEM_CLASS_ARMOR) + else if (spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR) { // Check if player is wearing shield Item* item = player->GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); - if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetTemplate()->SubClass) & spellProto->EquippedItemSubClassMask)) + if (!item || item->IsBroken() || item->GetTemplate()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetTemplate()->SubClass) & spellInfo->EquippedItemSubClassMask)) return false; } } + + return true; +} + +bool Unit::RollProcResult(Unit* victim, Aura* aura, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const* spellProcEvent) +{ + SpellInfo const* spellInfo = aura->GetSpellInfo(); // Get chance from spell - float chance = float(spellProto->ProcChance); + float chance = float(spellInfo->ProcChance); // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance; if (spellProcEvent && spellProcEvent->customChance) chance = spellProcEvent->customChance; @@ -15179,19 +14862,18 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const if (!isVictim) { uint32 weaponSpeed = GetAttackTime(attType); - chance = GetPPMProcChance(weaponSpeed, spellProcEvent->ppmRate, spellProto); + chance = GetPPMProcChance(weaponSpeed, spellProcEvent->ppmRate, spellInfo); } else if (victim) { uint32 weaponSpeed = victim->GetAttackTime(attType); - chance = victim->GetPPMProcChance(weaponSpeed, spellProcEvent->ppmRate, spellProto); + chance = victim->GetPPMProcChance(weaponSpeed, spellProcEvent->ppmRate, spellInfo); } } // Apply chance modifer aura if (Player* modOwner = GetSpellModOwner()) - { - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance); - } + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CHANCE_OF_SUCCESS, chance); + return roll_chance_f(chance); } @@ -15502,12 +15184,19 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) Player* creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself(); /// @todo do instance binding anyway if the charmer/owner is offline - if (instanceMap->IsDungeon() && creditedPlayer) + if (instanceMap->IsDungeon() && (creditedPlayer || this == victim)) { if (instanceMap->IsRaidOrHeroicDungeon()) { if (creature->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND) - ((InstanceMap*)instanceMap)->PermBindAllPlayers(creditedPlayer); + { + // if the boss killed itself we still need to bind players to the instance + if (!creditedPlayer && instanceMap->HavePlayers()) + creditedPlayer = instanceMap->GetPlayers().getFirst()->GetSource(); + + if (creditedPlayer) + ((InstanceMap*)instanceMap)->PermBindAllPlayers(creditedPlayer); + } } else { @@ -15515,7 +15204,8 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) // until the players leave the instance time_t resettime = creature->GetRespawnTimeEx() + 2 * HOUR; if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(creature->GetInstanceId())) - if (save->GetResetTime() < resettime) save->SetResetTime(resettime); + if (save->GetResetTime() < resettime) + save->SetResetTime(resettime); } } } @@ -15905,11 +15595,21 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au ToCreature()->AI()->OnCharmed(true); GetMotionMaster()->MoveIdle(); } - else + else if (Player* player = ToPlayer()) { - Player* player = ToPlayer(); if (player->isAFK()) player->ToggleAFK(); + + if (charmer->GetTypeId() == TYPEID_UNIT) // we are charmed by a creature + { + // change AI to charmed AI on next Update tick + NeedChangeAI = true; + if (IsAIEnabled) + { + IsAIEnabled = false; + player->AI()->OnCharmed(true); + } + } player->SetClientControl(this, false); } @@ -15940,7 +15640,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au case CHARM_TYPE_POSSESS: AddUnitState(UNIT_STATE_POSSESSED); SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); - charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + charmer->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); playerCharmer->SetClientControl(this, true); playerCharmer->PossessSpellInitialize(); break; @@ -15951,7 +15651,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au if (cinfo && cinfo->type == CREATURE_TYPE_DEMON) { // to prevent client crash - SetByteValue(UNIT_FIELD_BYTES_0, 1, (uint8)CLASS_MAGE); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, (uint8)CLASS_MAGE); // just to enable stat window if (GetCharmInfo()) @@ -16043,7 +15743,7 @@ void Unit::RemoveCharmedBy(Unit* charmer) case CHARM_TYPE_POSSESS: playerCharmer->SetClientControl(this, false); playerCharmer->SetClientControl(charmer, true); - charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + charmer->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); ClearUnitState(UNIT_STATE_POSSESSED); break; @@ -16053,7 +15753,7 @@ void Unit::RemoveCharmedBy(Unit* charmer) CreatureTemplate const* cinfo = ToCreature()->GetCreatureTemplate(); if (cinfo && cinfo->type == CREATURE_TYPE_DEMON) { - SetByteValue(UNIT_FIELD_BYTES_0, 1, uint8(cinfo->unit_class)); + SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS, uint8(cinfo->unit_class)); if (GetCharmInfo()) GetCharmInfo()->SetPetNumber(0, true); else @@ -16067,7 +15767,14 @@ void Unit::RemoveCharmedBy(Unit* charmer) } if (Player* player = ToPlayer()) + { + if (charmer->GetTypeId() == TYPEID_UNIT) // charmed by a creature, this means we had PlayerAI + { + NeedChangeAI = true; + IsAIEnabled = false; + } player->SetClientControl(this, true); + } // a guardian should always have charminfo if (playerCharmer && this != charmer->GetFirstControlled()) @@ -16176,8 +15883,8 @@ bool Unit::IsInPartyWith(Unit const* unit) const if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER) return u1->ToPlayer()->IsInSameGroupWith(u2->ToPlayer()); - else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER) || - (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER)) + else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) || + (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT)) return true; else return false; @@ -16195,8 +15902,8 @@ bool Unit::IsInRaidWith(Unit const* unit) const if (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_PLAYER) return u1->ToPlayer()->IsInSameRaidWith(u2->ToPlayer()); - else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER) || - (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PARTY_MEMBER)) + else if ((u2->GetTypeId() == TYPEID_PLAYER && u1->GetTypeId() == TYPEID_UNIT && u1->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT) || + (u1->GetTypeId() == TYPEID_PLAYER && u2->GetTypeId() == TYPEID_UNIT && u2->ToCreature()->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT)) return true; else return false; @@ -16564,7 +16271,7 @@ uint32 Unit::GetModelForForm(ShapeshiftForm form) const // Based on Hair color if (getRace() == RACE_NIGHTELF) { - uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); + uint8 hairColor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID); switch (hairColor) { case 7: // Violet @@ -16585,7 +16292,7 @@ uint32 Unit::GetModelForForm(ShapeshiftForm form) const // Based on Skin color else if (getRace() == RACE_TAUREN) { - uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); + uint8 skinColor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID); // Male if (getGender() == GENDER_MALE) { @@ -16644,7 +16351,7 @@ uint32 Unit::GetModelForForm(ShapeshiftForm form) const // Based on Hair color if (getRace() == RACE_NIGHTELF) { - uint8 hairColor = GetByteValue(PLAYER_BYTES, 3); + uint8 hairColor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID); switch (hairColor) { case 0: // Green @@ -16664,7 +16371,7 @@ uint32 Unit::GetModelForForm(ShapeshiftForm form) const // Based on Skin color else if (getRace() == RACE_TAUREN) { - uint8 skinColor = GetByteValue(PLAYER_BYTES, 0); + uint8 skinColor = GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID); // Male if (getGender() == GENDER_MALE) { @@ -17078,7 +16785,7 @@ void Unit::_ExitVehicle(Position const* exitPosition) Movement::MoveSplineInit init(this); // Creatures without inhabit type air should begin falling after exiting the vehicle - if (GetTypeId() == TYPEID_UNIT && !CanFly() && height > GetMap()->GetWaterOrGroundLevel(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), &height) + 0.1f) + if (GetTypeId() == TYPEID_UNIT && !CanFly() && height > GetMap()->GetWaterOrGroundLevel(GetPhaseMask(), pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), &height) + 0.1f) init.SetFall(); init.MoveTo(pos.GetPositionX(), pos.GetPositionY(), height, false); @@ -17541,7 +17248,7 @@ void Unit::SetFacingToObject(WorldObject const* object) /// @todo figure out under what conditions creature will move towards object instead of facing it where it currently is. Movement::MoveSplineInit init(this); - init.MoveTo(GetPositionX(), GetPositionY(), GetPositionZMinusOffset()); + init.MoveTo(GetPositionX(), GetPositionY(), GetPositionZMinusOffset(), false); init.SetFacing(GetAngle(object)); // when on transport, GetAngle will still return global coordinates (and angle) that needs transforming init.Launch(); } @@ -17555,7 +17262,6 @@ bool Unit::SetWalk(bool enable) AddUnitMovementFlag(MOVEMENTFLAG_WALKING); else RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); - return true; } @@ -17570,15 +17276,7 @@ bool Unit::SetDisableGravity(bool disable, bool /*packetOnly = false*/) RemoveUnitMovementFlag(MOVEMENTFLAG_FALLING); } else - { RemoveUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY); - if (!HasUnitMovementFlag(MOVEMENTFLAG_CAN_FLY)) - { - m_movementInfo.SetFallTime(0); - AddUnitMovementFlag(MOVEMENTFLAG_FALLING); - } - } - return true; } @@ -17591,7 +17289,6 @@ bool Unit::SetSwim(bool enable) AddUnitMovementFlag(MOVEMENTFLAG_SWIMMING); else RemoveUnitMovementFlag(MOVEMENTFLAG_SWIMMING); - return true; } @@ -17606,15 +17303,7 @@ bool Unit::SetCanFly(bool enable, bool /*packetOnly = false */) RemoveUnitMovementFlag(MOVEMENTFLAG_FALLING); } else - { RemoveUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_MASK_MOVING_FLY); - if (!IsLevitating()) - { - m_movementInfo.SetFallTime(0); - AddUnitMovementFlag(MOVEMENTFLAG_FALLING); - } - } - return true; } @@ -17627,7 +17316,6 @@ bool Unit::SetWaterWalking(bool enable, bool /*packetOnly = false */) AddUnitMovementFlag(MOVEMENTFLAG_WATERWALKING); else RemoveUnitMovementFlag(MOVEMENTFLAG_WATERWALKING); - return true; } @@ -17640,7 +17328,6 @@ bool Unit::SetFeatherFall(bool enable, bool /*packetOnly = false */) AddUnitMovementFlag(MOVEMENTFLAG_FALLING_SLOW); else RemoveUnitMovementFlag(MOVEMENTFLAG_FALLING_SLOW); - return true; } @@ -17668,7 +17355,6 @@ bool Unit::SetHover(bool enable, bool /*packetOnly = false*/) UpdateHeight(newZ); } } - return true; } diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index 4565160dc93..0f48f31b9c0 100644 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -76,6 +76,7 @@ enum SpellAuraInterruptFlags AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT = 0x00800000, // 23 removed by entering pvp combat AURA_INTERRUPT_FLAG_DIRECT_DAMAGE = 0x01000000, // 24 removed by any direct damage AURA_INTERRUPT_FLAG_LANDING = 0x02000000, // 25 removed by hitting the ground + AURA_INTERRUPT_FLAG_LEAVE_COMBAT = 0x80000000, // 31 removed by leaving combat AURA_INTERRUPT_FLAG_NOT_VICTIM = (AURA_INTERRUPT_FLAG_HITBYSPELL | AURA_INTERRUPT_FLAG_TAKE_DAMAGE | AURA_INTERRUPT_FLAG_DIRECT_DAMAGE) }; @@ -190,6 +191,30 @@ enum UnitStandFlags UNIT_STAND_FLAGS_ALL = 0xFF }; +enum UnitBytes0Offsets +{ + UNIT_BYTES_0_OFFSET_RACE = 0, + UNIT_BYTES_0_OFFSET_CLASS = 1, + UNIT_BYTES_0_OFFSET_GENDER = 2, + UNIT_BYTES_0_OFFSET_POWER_TYPE = 3, +}; + +enum UnitBytes1Offsets +{ + UNIT_BYTES_1_OFFSET_STAND_STATE = 0, + UNIT_BYTES_1_OFFSET_PET_TALENTS = 1, + UNIT_BYTES_1_OFFSET_VIS_FLAG = 2, + UNIT_BYTES_1_OFFSET_ANIM_TIER = 3 +}; + +enum UnitBytes2Offsets +{ + UNIT_BYTES_2_OFFSET_SHEATH_STATE = 0, + UNIT_BYTES_2_OFFSET_PVP_FLAG = 1, + UNIT_BYTES_2_OFFSET_PET_FLAG = 2, + UNIT_BYTES_2_OFFSET_SHAPESHIFT = 3, +}; + // byte flags value (UNIT_FIELD_BYTES_1, 3) enum UnitBytes1_Flags { @@ -533,10 +558,10 @@ enum UnitMoveType #define MAX_MOVE_TYPE 9 -extern float baseMoveSpeed[MAX_MOVE_TYPE]; -extern float playerBaseMoveSpeed[MAX_MOVE_TYPE]; +TC_GAME_API extern float baseMoveSpeed[MAX_MOVE_TYPE]; +TC_GAME_API extern float playerBaseMoveSpeed[MAX_MOVE_TYPE]; -enum WeaponAttackType +enum WeaponAttackType : uint8 { BASE_ATTACK = 0, OFF_ATTACK = 1, @@ -586,11 +611,11 @@ enum DamageEffectType }; // Value masks for UNIT_FIELD_FLAGS -enum UnitFlags +enum UnitFlags : uint32 { UNIT_FLAG_SERVER_CONTROLLED = 0x00000001, // set only when unit movement is controlled by server - by SPLINE/MONSTER_MOVE packets, together with UNIT_FLAG_STUNNED; only set to units controlled by client; client function CGUnit_C::IsClientControlled returns false when set for owner UNIT_FLAG_NON_ATTACKABLE = 0x00000002, // not attackable - UNIT_FLAG_DISABLE_MOVE = 0x00000004, + UNIT_FLAG_REMOVE_CLIENT_CONTROL = 0x00000004, // This is a legacy flag used to disable movement player's movement while controlling other units, SMSG_CLIENT_CONTROL replaces this functionality clientside now. CONFUSED and FLEEING flags have the same effect on client movement asDISABLE_MOVE_CONTROL in addition to preventing spell casts/autoattack (they all allow climbing steeper hills and emotes while moving) UNIT_FLAG_PVP_ATTACKABLE = 0x00000008, // allow apply pvp rules to attackable state in addition to faction dependent state UNIT_FLAG_RENAME = 0x00000010, UNIT_FLAG_PREPARATION = 0x00000020, // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP @@ -602,7 +627,7 @@ enum UnitFlags UNIT_FLAG_PET_IN_COMBAT = 0x00000800, // in combat?, 2.0.8 UNIT_FLAG_PVP = 0x00001000, // changed in 3.0.3 UNIT_FLAG_SILENCED = 0x00002000, // silenced, 2.1.1 - UNIT_FLAG_UNK_14 = 0x00004000, // 2.0.8 + UNIT_FLAG_CANNOT_SWIM = 0x00004000, // 2.0.8 UNIT_FLAG_UNK_15 = 0x00008000, UNIT_FLAG_UNK_16 = 0x00010000, UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok @@ -714,14 +739,13 @@ enum MovementFlags MOVEMENTFLAG_FALLING_SLOW = 0x20000000, // active rogue safe fall spell (passive) MOVEMENTFLAG_HOVER = 0x40000000, // hover, cannot jump - /// @todo Check if PITCH_UP and PITCH_DOWN really belong here.. MOVEMENTFLAG_MASK_MOVING = MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT | - MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN | MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | + MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | MOVEMENTFLAG_SPLINE_ELEVATION, MOVEMENTFLAG_MASK_TURNING = - MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT, + MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN, MOVEMENTFLAG_MASK_MOVING_FLY = MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING, @@ -826,7 +850,7 @@ struct CleanDamage struct CalcDamageInfo; -class DamageInfo +class TC_GAME_API DamageInfo { private: Unit* const m_attacker; @@ -889,7 +913,7 @@ public: SpellSchoolMask GetSchoolMask() const { return _schoolMask; }; }; -class ProcEventInfo +class TC_GAME_API ProcEventInfo { public: ProcEventInfo(Unit* actor, Unit* actionTarget, Unit* procTarget, uint32 typeMask, @@ -947,7 +971,7 @@ struct CalcDamageInfo }; // Spell damage info structure based on structure sending in SMSG_SPELLNONMELEEDAMAGELOG opcode -struct SpellNonMeleeDamage +struct TC_GAME_API SpellNonMeleeDamage { SpellNonMeleeDamage(Unit* _attacker, Unit* _target, uint32 _SpellID, uint32 _schoolMask) : target(_target), attacker(_attacker), SpellID(_SpellID), damage(0), overkill(0), schoolMask(_schoolMask), @@ -1043,7 +1067,7 @@ enum ReactStates REACT_AGGRESSIVE = 2 }; -enum CommandStates +enum CommandStates : uint8 { COMMAND_STAY = 0, COMMAND_FOLLOW = 1, @@ -1108,7 +1132,7 @@ enum ActionBarIndex #define MAX_UNIT_ACTION_BAR_INDEX (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START) -struct CharmInfo +struct TC_GAME_API CharmInfo { public: explicit CharmInfo(Unit* unit); @@ -1210,7 +1234,7 @@ enum PlayerTotemType struct SpellProcEventEntry; // used only privately -class Unit : public WorldObject +class TC_GAME_API Unit : public WorldObject { public: typedef std::set<Unit*> AttackerSet; @@ -1265,9 +1289,8 @@ class Unit : public WorldObject bool CanDualWield() const { return m_canDualWield; } virtual void SetCanDualWield(bool value) { m_canDualWield = value; } float GetCombatReach() const { return m_floatValues[UNIT_FIELD_COMBATREACH]; } - float GetMeleeReach() const; bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; - bool IsWithinMeleeRange(const Unit* obj, float dist = MELEE_RANGE) const; + bool IsWithinMeleeRange(Unit const* obj) const; void GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const; uint32 m_extraAttacks; bool m_canDualWield; @@ -1276,7 +1299,7 @@ class Unit : public WorldObject void _removeAttacker(Unit* pAttacker); // must be called only from Unit::AttackStop() Unit* getAttackerForHelper() const; // If someone wants to help, who to give them bool Attack(Unit* victim, bool meleeAttack); - void MustReacquireTarget() { m_shouldReacquireTarget = true; } // flags the Unit for forced target reacquisition in the next ::Attack call + void MustReacquireTarget() { m_shouldReacquireTarget = true; } // flags the Unit for forced (client displayed) target reacquisition in the next ::Attack call void CastStop(uint32 except_spellid = 0); bool AttackStop(); void RemoveAllAttackers(); @@ -1314,11 +1337,11 @@ class Unit : public WorldObject uint8 getLevel() const { return uint8(GetUInt32Value(UNIT_FIELD_LEVEL)); } uint8 getLevelForTarget(WorldObject const* /*target*/) const override { return getLevel(); } void SetLevel(uint8 lvl); - uint8 getRace() const { return GetByteValue(UNIT_FIELD_BYTES_0, 0); } + uint8 getRace() const { return GetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_RACE); } uint32 getRaceMask() const { return 1 << (getRace()-1); } - uint8 getClass() const { return GetByteValue(UNIT_FIELD_BYTES_0, 1); } + uint8 getClass() const { return GetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_CLASS); } uint32 getClassMask() const { return 1 << (getClass()-1); } - uint8 getGender() const { return GetByteValue(UNIT_FIELD_BYTES_0, 2); } + uint8 getGender() const { return GetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER); } float GetStat(Stats stat) const { return float(GetUInt32Value(UNIT_FIELD_STAT0+stat)); } void SetStat(Stats stat, int32 val) { SetStatInt32Value(UNIT_FIELD_STAT0+stat, val); } @@ -1347,7 +1370,7 @@ class Unit : public WorldObject int32 ModifyHealth(int32 val); int32 GetHealthGain(int32 dVal); - Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, 3)); } + Powers getPowerType() const { return Powers(GetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE)); } void setPowerType(Powers power); uint32 GetPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_POWER1 +power); } uint32 GetMaxPower(Powers power) const { return GetUInt32Value(UNIT_FIELD_MAXPOWER1+power); } @@ -1383,11 +1406,12 @@ class Unit : public WorldObject bool IsContestedGuard() const; bool IsPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); } bool IsFFAPvP() const { return HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); } - void SetPvP(bool state); + virtual void SetPvP(bool state); + uint32 GetCreatureType() const; uint32 GetCreatureTypeMask() const; - uint8 getStandState() const { return GetByteValue(UNIT_FIELD_BYTES_1, 0); } + uint8 GetStandState() const { return GetByteValue(UNIT_FIELD_BYTES_1, 0); } bool IsSitState() const; bool IsStandState() const; void SetStandState(uint8 state); @@ -1561,7 +1585,7 @@ class Unit : public WorldObject void SendTeleportPacket(Position& pos); virtual bool UpdatePosition(float x, float y, float z, float ang, bool teleport = false); // returns true if unit's position really changed - bool UpdatePosition(const Position &pos, bool teleport = false); + virtual bool UpdatePosition(const Position &pos, bool teleport = false); void UpdateOrientation(float orientation); void UpdateHeight(float newZ); @@ -1601,7 +1625,7 @@ class Unit : public WorldObject bool IsAlive() const { return (m_deathState == ALIVE); } bool isDying() const { return (m_deathState == JUST_DIED); } bool isDead() const { return (m_deathState == DEAD || m_deathState == CORPSE); } - bool IsGhouled() const { return HasAura(46619 /*SPELL_DK_RAISE_ALLY*/); } + bool IsGhouled() const; DeathState getDeathState() const { return m_deathState; } virtual void setDeathState(DeathState s); // overwrited in Creature/Player/Pet @@ -1659,7 +1683,8 @@ class Unit : public WorldObject CharmInfo* InitCharmInfo(); void DeleteCharmInfo(); void UpdateCharmAI(); - //Player* GetMoverSource() const; + Unit* GetMover() const; + Player* GetPlayerMover() const; Player* m_movedPlayer; SharedVisionList const& GetSharedVisionList() { return m_sharedVision; } void AddPlayerToVision(Player* player); @@ -1704,6 +1729,16 @@ class Unit : public WorldObject void RemoveAura(AuraApplication * aurApp, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); void RemoveAura(Aura* aur, AuraRemoveMode mode = AURA_REMOVE_BY_DEFAULT); + // Convenience methods removing auras by predicate + void RemoveAppliedAuras(std::function<bool(AuraApplication const*)> const& check); + void RemoveOwnedAuras(std::function<bool(Aura const*)> const& check); + + // Optimized overloads taking advantage of map key + void RemoveAppliedAuras(uint32 spellId, std::function<bool(AuraApplication const*)> const& check); + void RemoveOwnedAuras(uint32 spellId, std::function<bool(Aura const*)> const& check); + + void RemoveAurasByType(AuraType auraType, std::function<bool(AuraApplication const*)> const& check); + void RemoveAurasDueToSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); void RemoveAuraFromStack(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, ObjectGuid casterGUID, Unit* dispeller, uint8 chargesRemoved = 1); @@ -1720,6 +1755,7 @@ class Unit : public WorldObject void RemoveAreaAurasDueToLeaveWorld(); void RemoveAllAuras(); void RemoveArenaAuras(); + void RemoveAurasOnEvade(); void RemoveAllAurasOnDeath(); void RemoveAllAurasRequiringDeadTarget(); void RemoveAllAurasExceptType(AuraType type); @@ -1821,6 +1857,9 @@ class Unit : public WorldObject Spell* FindCurrentSpellBySpellId(uint32 spell_id) const; int32 GetCurrentSpellCastTime(uint32 spell_id) const; + // Check if our current channel spell has attribute SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING + bool CanMoveDuringChannel() const; + SpellHistory* GetSpellHistory() { return m_spellHistory; } SpellHistory const* GetSpellHistory() const { return m_spellHistory; } @@ -1983,10 +2022,11 @@ class Unit : public WorldObject void CalcAbsorbResist(Unit* victim, SpellSchoolMask schoolMask, DamageEffectType damagetype, uint32 const damage, uint32* absorb, uint32* resist, SpellInfo const* spellInfo = NULL); void CalcHealAbsorb(Unit* victim, SpellInfo const* spellInfo, uint32& healAmount, uint32& absorb); - void UpdateSpeed(UnitMoveType mtype, bool forced); + void UpdateSpeed(UnitMoveType mtype); float GetSpeed(UnitMoveType mtype) const; float GetSpeedRate(UnitMoveType mtype) const { return m_speed_rate[mtype]; } - void SetSpeed(UnitMoveType mtype, float rate, bool forced = false); + void SetSpeed(UnitMoveType mtype, float newValue); + void SetSpeedRate(UnitMoveType mtype, float rate); float ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const; int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = NULL) const; @@ -2130,11 +2170,11 @@ class Unit : public WorldObject virtual void Yell(std::string const& text, Language language, WorldObject const* target = nullptr); virtual void TextEmote(std::string const& text, WorldObject const* target = nullptr, bool isBossEmote = false); virtual void Whisper(std::string const& text, Language language, Player* target, bool isBossWhisper = false); - void Talk(uint32 textId, ChatMsg msgType, float textRange, WorldObject const* target); - void Say(uint32 textId, WorldObject const* target = nullptr); - void Yell(uint32 textId, WorldObject const* target = nullptr); - void TextEmote(uint32 textId, WorldObject const* target = nullptr, bool isBossEmote = false); - void Whisper(uint32 textId, Player* target, bool isBossWhisper = false); + virtual void Talk(uint32 textId, ChatMsg msgType, float textRange, WorldObject const* target); + virtual void Say(uint32 textId, WorldObject const* target = nullptr); + virtual void Yell(uint32 textId, WorldObject const* target = nullptr); + virtual void TextEmote(uint32 textId, WorldObject const* target = nullptr, bool isBossEmote = false); + virtual void Whisper(uint32 textId, Player* target, bool isBossWhisper = false); protected: explicit Unit (bool isWorldObject); @@ -2214,11 +2254,12 @@ class Unit : public WorldObject void DisableSpline(); private: - bool IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const* & spellProcEvent); - bool HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); - bool HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown, bool * handled); - bool HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown); - bool HandleOverrideClassScriptAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 cooldown); + bool IsTriggeredAtSpellProcEvent(Unit* victim, Aura* aura, SpellInfo const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent); + bool RollProcResult(Unit* victim, Aura* aura, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const* spellProcEvent); + bool HandleDummyAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, Milliseconds& cooldown); + bool HandleAuraProc(Unit* victim, uint32 damage, Aura* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx, bool* handled); + bool HandleProcTriggerSpell(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell, uint32 procFlag, uint32 procEx); + bool HandleOverrideClassScriptAuraProc(Unit* victim, uint32 damage, AuraEffect* triggeredByAura, SpellInfo const* procSpell); bool HandleAuraRaidProcFromChargeWithValue(AuraEffect* triggeredByAura); bool HandleAuraRaidProcFromCharge(AuraEffect* triggeredByAura); diff --git a/src/server/game/Entities/Vehicle/Vehicle.cpp b/src/server/game/Entities/Vehicle/Vehicle.cpp index 9cf485322f2..1c5299f4798 100755 --- a/src/server/game/Entities/Vehicle/Vehicle.cpp +++ b/src/server/game/Entities/Vehicle/Vehicle.cpp @@ -238,7 +238,7 @@ void Vehicle::RemoveAllPassengers() while (!_pendingJoinEvents.empty()) { VehicleJoinEvent* e = _pendingJoinEvents.front(); - e->to_Abort = true; + e->ScheduleAbort(); e->Target = eventVehicle; _pendingJoinEvents.pop_front(); } @@ -429,7 +429,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) if (seat == Seats.end()) // no available seat { - e->to_Abort = true; + e->ScheduleAbort(); return false; } @@ -441,7 +441,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) seat = Seats.find(seatId); if (seat == Seats.end()) { - e->to_Abort = true; + e->ScheduleAbort(); return false; } @@ -532,6 +532,9 @@ void Vehicle::RelocatePassengers() { ASSERT(_me->GetMap()); + std::vector<std::pair<Unit*, Position>> seatRelocation; + seatRelocation.reserve(Seats.size()); + // not sure that absolute position calculation is correct, it must depend on vehicle pitch angle for (SeatMap::const_iterator itr = Seats.begin(); itr != Seats.end(); ++itr) { @@ -542,9 +545,12 @@ void Vehicle::RelocatePassengers() float px, py, pz, po; passenger->m_movementInfo.transport.pos.GetPosition(px, py, pz, po); CalculatePassengerPosition(px, py, pz, &po); - passenger->UpdatePosition(px, py, pz, po); + seatRelocation.emplace_back(passenger, Position(px, py, pz, po)); } } + + for (auto const& pair : seatRelocation) + pair.first->UpdatePosition(pair.second); } /** @@ -701,7 +707,7 @@ void Vehicle::RemovePendingEventsForSeat(int8 seatId) { if ((*itr)->Seat->first == seatId) { - (*itr)->to_Abort = true; + (*itr)->ScheduleAbort(); _pendingJoinEvents.erase(itr++); } else @@ -726,7 +732,7 @@ void Vehicle::RemovePendingEventsForPassenger(Unit* passenger) { if ((*itr)->Passenger == passenger) { - (*itr)->to_Abort = true; + (*itr)->ScheduleAbort(); _pendingJoinEvents.erase(itr++); } else diff --git a/src/server/game/Entities/Vehicle/Vehicle.h b/src/server/game/Entities/Vehicle/Vehicle.h index cd28c4082d4..f8992708a46 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.h +++ b/src/server/game/Entities/Vehicle/Vehicle.h @@ -29,7 +29,7 @@ struct VehicleEntry; class Unit; class VehicleJoinEvent; -class Vehicle : public TransportBase +class TC_GAME_API Vehicle : public TransportBase { protected: friend bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry); @@ -118,7 +118,7 @@ class Vehicle : public TransportBase PendingJoinEventContainer _pendingJoinEvents; ///< Collection of delayed join events for prospective passengers }; -class VehicleJoinEvent : public BasicEvent +class TC_GAME_API VehicleJoinEvent : public BasicEvent { friend class Vehicle; protected: diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index b2871786034..bb8e89d4829 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -29,6 +29,12 @@ #include "UnitAI.h" #include "GameObjectAI.h" +GameEventMgr* GameEventMgr::instance() +{ + static GameEventMgr instance; + return &instance; +} + bool GameEventMgr::CheckOneGameEvent(uint16 entry) const { switch (mGameEvent[entry].state) @@ -221,7 +227,7 @@ void GameEventMgr::LoadFromDB() uint8 event_id = fields[0].GetUInt8(); if (event_id == 0) { - TC_LOG_ERROR("sql.sql", "`game_event` game event entry 0 is reserved and can't be used."); + TC_LOG_ERROR("sql.sql", "`game_event`: game event entry 0 is reserved and can't be used."); continue; } @@ -240,7 +246,7 @@ void GameEventMgr::LoadFromDB() if (pGameEvent.length == 0 && pGameEvent.state == GAMEEVENT_NORMAL) // length>0 is validity check { - TC_LOG_ERROR("sql.sql", "`game_event` game event id (%i) isn't a world event and has length = 0, thus it can't be used.", event_id); + TC_LOG_ERROR("sql.sql", "`game_event`: game event id (%i) is not a world event and has length = 0, thus cannot be used.", event_id); continue; } @@ -248,7 +254,7 @@ void GameEventMgr::LoadFromDB() { if (!sHolidaysStore.LookupEntry(pGameEvent.holiday_id)) { - TC_LOG_ERROR("sql.sql", "`game_event` game event id (%i) have not existed holiday id %u.", event_id, pGameEvent.holiday_id); + TC_LOG_ERROR("sql.sql", "`game_event`: game event id (%i) contains nonexisting holiday id %u.", event_id, pGameEvent.holiday_id); pGameEvent.holiday_id = HOLIDAY_NONE; } } @@ -259,7 +265,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } @@ -283,7 +289,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_save` game event entry (%i) is out of range compared to max event entry in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_save`: game event entry (%i) is out of range compared to max event entry in `game_event`.", event_id); continue; } @@ -294,7 +300,7 @@ void GameEventMgr::LoadFromDB() } else { - TC_LOG_ERROR("sql.sql", "game_event_save includes event save for non-worldevent id %u", event_id); + TC_LOG_ERROR("sql.sql", "game_event_save includes event save for non-worldevent id %u.", event_id); continue; } @@ -302,7 +308,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u game event saves in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u game event saves in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -326,7 +332,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_prerequisite` game event id (%i) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_prerequisite`: game event id (%i) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -335,14 +341,14 @@ void GameEventMgr::LoadFromDB() uint16 prerequisite_event = fields[1].GetUInt32(); if (prerequisite_event >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_prerequisite` game event prerequisite id (%i) is out of range compared to max event id in `game_event`", prerequisite_event); + TC_LOG_ERROR("sql.sql", "`game_event_prerequisite`: game event prerequisite id (%i) is out of range compared to max event id in `game_event`.", prerequisite_event); continue; } mGameEvent[event_id].prerequisite_events.insert(prerequisite_event); } else { - TC_LOG_ERROR("sql.sql", "game_event_prerequisiste includes event entry for non-worldevent id %u", event_id); + TC_LOG_ERROR("sql.sql", "game_event_prerequisiste includes event entry for non-worldevent id %u.", event_id); continue; } @@ -350,7 +356,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u game event prerequisites in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u game event prerequisites in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -363,7 +369,7 @@ void GameEventMgr::LoadFromDB() QueryResult result = WorldDatabase.Query("SELECT guid, eventEntry FROM game_event_creature"); if (!result) - TC_LOG_INFO("server.loading", ">> Loaded 0 creatures in game events. DB table `game_event_creature` is empty"); + TC_LOG_INFO("server.loading", ">> Loaded 0 creatures in game events. DB table `game_event_creature` is empty."); else { uint32 count = 0; @@ -385,7 +391,7 @@ void GameEventMgr::LoadFromDB() if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { - TC_LOG_ERROR("sql.sql", "`game_event_creature` game event id (%i) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_creature`: game event id (%i) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -396,7 +402,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u creatures in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u creatures in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -431,7 +437,7 @@ void GameEventMgr::LoadFromDB() if (internal_event_id < 0 || internal_event_id >= int32(mGameEventGameobjectGuids.size())) { - TC_LOG_ERROR("sql.sql", "`game_event_gameobject` game event id (%i) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_gameobject`: game event id (%i) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -442,7 +448,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u gameobjects in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u gameobjects in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -469,7 +475,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventModelEquip.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_model_equip` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_model_equip`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -485,7 +491,7 @@ void GameEventMgr::LoadFromDB() int8 equipId = static_cast<int8>(newModelEquipSet.equipment_id); if (!sObjectMgr->GetEquipmentInfo(entry, equipId)) { - TC_LOG_ERROR("sql.sql", "Table `game_event_model_equip` have creature (Guid: %u, entry: %u) with equipment_id %u not found in table `creature_equip_template`, set to no equipment.", + TC_LOG_ERROR("sql.sql", "Table `game_event_model_equip` contains creature (Guid: %u, entry: %u) with equipment_id %u not found in table `creature_equip_template`. Setting entry to no equipment.", guid, entry, newModelEquipSet.equipment_id); continue; } @@ -497,7 +503,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u model/equipment changes in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u model/equipment changes in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -523,7 +529,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventCreatureQuests.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_creature_quest` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_creature_quest`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -534,7 +540,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -560,7 +566,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventGameObjectQuests.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_gameobject_quest` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_gameobject_quest`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -571,7 +577,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -598,7 +604,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_quest_condition` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_quest_condition`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -610,7 +616,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u quest event conditions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u quest event conditions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -635,7 +641,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_condition` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_condition`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -648,7 +654,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u conditions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u conditions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -673,7 +679,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_condition_save` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_condition_save`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -684,7 +690,7 @@ void GameEventMgr::LoadFromDB() } else { - TC_LOG_ERROR("sql.sql", "game_event_condition_save contains not present condition evt id %u cond id %u", event_id, condition); + TC_LOG_ERROR("sql.sql", "game_event_condition_save contains not present condition event id %u condition id %u.", event_id, condition); continue; } @@ -692,7 +698,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u condition saves in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u condition saves in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -718,7 +724,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_npcflag` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_npcflag`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -728,7 +734,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u npcflags in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u npcflags in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -753,13 +759,13 @@ void GameEventMgr::LoadFromDB() if (!sObjectMgr->GetQuestTemplate(questId)) { - TC_LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation` quest id (%u) does not exist in `quest_template`", questId); + TC_LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation`: quest id (%u) does not exist in `quest_template`.", questId); continue; } if (eventEntry >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation` event id (%u) is out of range compared to max event in `game_event`", eventEntry); + TC_LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation`: event id (%u) is out of range compared to max event in `game_event`.", eventEntry); continue; } @@ -768,7 +774,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u quests additions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -792,7 +798,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventVendors.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_npc_vendor` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_npc_vendor`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -830,7 +836,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u vendor additions in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u vendor additions in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -854,7 +860,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - TC_LOG_ERROR("sql.sql", "`game_event_battleground_holiday` game event id (%u) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_battleground_holiday`: game event id (%u) is out of range compared to max event id in `game_event`.", event_id); continue; } @@ -864,7 +870,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u battleground holidays in game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u battleground holidays in game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } @@ -892,13 +898,13 @@ void GameEventMgr::LoadFromDB() if (internal_event_id < 0 || internal_event_id >= int32(mGameEventPoolIds.size())) { - TC_LOG_ERROR("sql.sql", "`game_event_pool` game event id (%i) is out of range compared to max event id in `game_event`", event_id); + TC_LOG_ERROR("sql.sql", "`game_event_pool`: game event id (%i) is out of range compared to max event id in `game_event`.", event_id); continue; } if (!sPoolMgr->CheckPool(entry)) { - TC_LOG_ERROR("sql.sql", "Pool Id (%u) has all creatures or gameobjects with explicit chance sum <>100 and no equal chance defined. The pool system cannot pick one to spawn.", entry); + TC_LOG_ERROR("sql.sql", "Pool Id (%u) has all creatures or gameobjects with explicit chance sum <> 100 and no equal chance defined. The pool system cannot pick one to spawn.", entry); continue; } @@ -909,7 +915,7 @@ void GameEventMgr::LoadFromDB() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u pools for game events in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u pools for game events in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } } } @@ -971,7 +977,7 @@ void GameEventMgr::StartArenaSeason() if (!result) { - TC_LOG_ERROR("gameevent", "ArenaSeason (%u) must be an existant Arena Season", season); + TC_LOG_ERROR("gameevent", "ArenaSeason (%u) must be an existing Arena Season.", season); return; } @@ -980,7 +986,7 @@ void GameEventMgr::StartArenaSeason() if (eventId >= mGameEvent.size()) { - TC_LOG_ERROR("gameevent", "EventEntry %u for ArenaSeason (%u) does not exists", eventId, season); + TC_LOG_ERROR("gameevent", "EventEntry %u for ArenaSeason (%u) does not exist.", eventId, season); return; } @@ -1171,7 +1177,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempt access to out of range mGameEventCreatureGuids element %i (size: %zu)", + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempted access to out of range mGameEventCreatureGuids element %i (size: %zu).", internal_event_id, mGameEventCreatureGuids.size()); return; } @@ -1198,7 +1204,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventGameobjectGuids.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempt access to out of range mGameEventGameobjectGuids element %i (size: %zu)", + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempted access to out of range mGameEventGameobjectGuids element %i (size: %zu).", internal_event_id, mGameEventGameobjectGuids.size()); return; } @@ -1231,7 +1237,7 @@ void GameEventMgr::GameEventSpawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventPoolIds.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempt access to out of range mGameEventPoolIds element %u (size: %zu)", + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventSpawn attempted access to out of range mGameEventPoolIds element %u (size: %zu).", internal_event_id, mGameEventPoolIds.size()); return; } @@ -1246,7 +1252,7 @@ void GameEventMgr::GameEventUnspawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempt access to out of range mGameEventCreatureGuids element %i (size: %zu)", + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempted access to out of range mGameEventCreatureGuids element %i (size: %zu).", internal_event_id, mGameEventCreatureGuids.size()); return; } @@ -1276,7 +1282,7 @@ void GameEventMgr::GameEventUnspawn(int16 event_id) if (internal_event_id < 0 || internal_event_id >= int32(mGameEventGameobjectGuids.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempt access to out of range mGameEventGameobjectGuids element %i (size: %zu)", + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempted access to out of range mGameEventGameobjectGuids element %i (size: %zu).", internal_event_id, mGameEventGameobjectGuids.size()); return; } @@ -1305,7 +1311,7 @@ void GameEventMgr::GameEventUnspawn(int16 event_id) } if (internal_event_id < 0 || internal_event_id >= int32(mGameEventPoolIds.size())) { - TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempt access to out of range mGameEventPoolIds element %u (size: %zu)", internal_event_id, mGameEventPoolIds.size()); + TC_LOG_ERROR("gameevent", "GameEventMgr::GameEventUnspawn attempted access to out of range mGameEventPoolIds element %u (size: %zu).", internal_event_id, mGameEventPoolIds.size()); return; } diff --git a/src/server/game/Events/GameEventMgr.h b/src/server/game/Events/GameEventMgr.h index b8d281dfdd7..44ed2fb1332 100644 --- a/src/server/game/Events/GameEventMgr.h +++ b/src/server/game/Events/GameEventMgr.h @@ -93,18 +93,14 @@ class Player; class Creature; class Quest; -class GameEventMgr +class TC_GAME_API GameEventMgr { private: GameEventMgr(); ~GameEventMgr() { } public: - static GameEventMgr* instance() - { - static GameEventMgr instance; - return &instance; - } + static GameEventMgr* instance(); typedef std::set<uint16> ActiveEvents; typedef std::vector<GameEventData> GameEventDataMap; @@ -186,8 +182,8 @@ class GameEventMgr #define sGameEventMgr GameEventMgr::instance() -bool IsHolidayActive(HolidayIds id); -bool IsEventActive(uint16 event_id); +TC_GAME_API bool IsHolidayActive(HolidayIds id); +TC_GAME_API bool IsEventActive(uint16 event_id); #endif diff --git a/src/server/game/Globals/ObjectAccessor.cpp b/src/server/game/Globals/ObjectAccessor.cpp index 762c9b9c28e..247c4943113 100644 --- a/src/server/game/Globals/ObjectAccessor.cpp +++ b/src/server/game/Globals/ObjectAccessor.cpp @@ -34,6 +34,53 @@ #include <boost/thread/shared_mutex.hpp> #include <boost/thread/locks.hpp> +template<class T> +void HashMapHolder<T>::Insert(T* o) +{ + boost::unique_lock<boost::shared_mutex> lock(*GetLock()); + + GetContainer()[o->GetGUID()] = o; +} + +template<class T> +void HashMapHolder<T>::Remove(T* o) +{ + boost::unique_lock<boost::shared_mutex> lock(*GetLock()); + + GetContainer().erase(o->GetGUID()); +} + +template<class T> +T* HashMapHolder<T>::Find(ObjectGuid guid) +{ + boost::shared_lock<boost::shared_mutex> lock(*GetLock()); + + typename MapType::iterator itr = GetContainer().find(guid); + return (itr != GetContainer().end()) ? itr->second : NULL; +} + +template<class T> +auto HashMapHolder<T>::GetContainer() -> MapType& +{ + static MapType _objectMap; + return _objectMap; +} + +template<class T> +boost::shared_mutex* HashMapHolder<T>::GetLock() +{ + static boost::shared_mutex _lock; + return &_lock; +} + +HashMapHolder<Player>::MapType const& ObjectAccessor::GetPlayers() +{ + return HashMapHolder<Player>::GetContainer(); +} + +template class TC_GAME_API HashMapHolder<Player>; +template class TC_GAME_API HashMapHolder<Transport>; + WorldObject* ObjectAccessor::GetWorldObject(WorldObject const& p, ObjectGuid const& guid) { switch (guid.GetHigh()) @@ -206,11 +253,6 @@ Player* ObjectAccessor::FindConnectedPlayerByName(std::string const& name) return NULL; } -HashMapHolder<Player>::MapType const& ObjectAccessor::GetPlayers() -{ - return HashMapHolder<Player>::GetContainer(); -} - void ObjectAccessor::SaveAllPlayers() { boost::shared_lock<boost::shared_mutex> lock(*HashMapHolder<Player>::GetLock()); @@ -219,14 +261,3 @@ void ObjectAccessor::SaveAllPlayers() for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) itr->second->SaveToDB(); } - -/// Define the static members of HashMapHolder - -template <class T> typename HashMapHolder<T>::MapType HashMapHolder<T>::_objectMap; -template <class T> boost::shared_mutex HashMapHolder<T>::_lock; - -/// Global definitions for the hashmap storage - -template class HashMapHolder<Player>; - -template class HashMapHolder<Transport>; diff --git a/src/server/game/Globals/ObjectAccessor.h b/src/server/game/Globals/ObjectAccessor.h index d8466dbb1bc..be7066c84a9 100644 --- a/src/server/game/Globals/ObjectAccessor.h +++ b/src/server/game/Globals/ObjectAccessor.h @@ -42,76 +42,56 @@ class WorldRunnable; class Transport; template <class T> -class HashMapHolder +class TC_GAME_API HashMapHolder { - public: - static_assert(std::is_same<Player, T>::value - || std::is_same<Transport, T>::value, - "Only Player and Transport can be registered in global HashMapHolder"); + //Non instanceable only static + HashMapHolder() { } - typedef std::unordered_map<ObjectGuid, T*> MapType; +public: + static_assert(std::is_same<Player, T>::value + || std::is_same<Transport, T>::value, + "Only Player and Transport can be registered in global HashMapHolder"); - static void Insert(T* o) - { - boost::unique_lock<boost::shared_mutex> lock(_lock); + typedef std::unordered_map<ObjectGuid, T*> MapType; - _objectMap[o->GetGUID()] = o; - } + static void Insert(T* o); - static void Remove(T* o) - { - boost::unique_lock<boost::shared_mutex> lock(_lock); + static void Remove(T* o); - _objectMap.erase(o->GetGUID()); - } + static T* Find(ObjectGuid guid); - static T* Find(ObjectGuid guid) - { - boost::shared_lock<boost::shared_mutex> lock(_lock); + static MapType& GetContainer(); - typename MapType::iterator itr = _objectMap.find(guid); - return (itr != _objectMap.end()) ? itr->second : NULL; - } - - static MapType& GetContainer() { return _objectMap; } - - static boost::shared_mutex* GetLock() { return &_lock; } - - private: - //Non instanceable only static - HashMapHolder() { } - - static boost::shared_mutex _lock; - static MapType _objectMap; + static boost::shared_mutex* GetLock(); }; namespace ObjectAccessor { // these functions return objects only if in map of specified object - WorldObject* GetWorldObject(WorldObject const&, ObjectGuid const&); - Object* GetObjectByTypeMask(WorldObject const&, ObjectGuid const&, uint32 typemask); - Corpse* GetCorpse(WorldObject const& u, ObjectGuid const& guid); - GameObject* GetGameObject(WorldObject const& u, ObjectGuid const& guid); - Transport* GetTransport(WorldObject const& u, ObjectGuid const& guid); - DynamicObject* GetDynamicObject(WorldObject const& u, ObjectGuid const& guid); - Unit* GetUnit(WorldObject const&, ObjectGuid const& guid); - Creature* GetCreature(WorldObject const& u, ObjectGuid const& guid); - Pet* GetPet(WorldObject const&, ObjectGuid const& guid); - Player* GetPlayer(Map const*, ObjectGuid const& guid); - Player* GetPlayer(WorldObject const&, ObjectGuid const& guid); - Creature* GetCreatureOrPetOrVehicle(WorldObject const&, ObjectGuid const&); + TC_GAME_API WorldObject* GetWorldObject(WorldObject const&, ObjectGuid const&); + TC_GAME_API Object* GetObjectByTypeMask(WorldObject const&, ObjectGuid const&, uint32 typemask); + TC_GAME_API Corpse* GetCorpse(WorldObject const& u, ObjectGuid const& guid); + TC_GAME_API GameObject* GetGameObject(WorldObject const& u, ObjectGuid const& guid); + TC_GAME_API Transport* GetTransport(WorldObject const& u, ObjectGuid const& guid); + TC_GAME_API DynamicObject* GetDynamicObject(WorldObject const& u, ObjectGuid const& guid); + TC_GAME_API Unit* GetUnit(WorldObject const&, ObjectGuid const& guid); + TC_GAME_API Creature* GetCreature(WorldObject const& u, ObjectGuid const& guid); + TC_GAME_API Pet* GetPet(WorldObject const&, ObjectGuid const& guid); + TC_GAME_API Player* GetPlayer(Map const*, ObjectGuid const& guid); + TC_GAME_API Player* GetPlayer(WorldObject const&, ObjectGuid const& guid); + TC_GAME_API Creature* GetCreatureOrPetOrVehicle(WorldObject const&, ObjectGuid const&); // these functions return objects if found in whole world // ACCESS LIKE THAT IS NOT THREAD SAFE - Player* FindPlayer(ObjectGuid const&); - Player* FindPlayerByName(std::string const& name); + TC_GAME_API Player* FindPlayer(ObjectGuid const&); + TC_GAME_API Player* FindPlayerByName(std::string const& name); // this returns Player even if he is not in world, for example teleporting - Player* FindConnectedPlayer(ObjectGuid const&); - Player* FindConnectedPlayerByName(std::string const& name); + TC_GAME_API Player* FindConnectedPlayer(ObjectGuid const&); + TC_GAME_API Player* FindConnectedPlayerByName(std::string const& name); // when using this, you must use the hashmapholder's lock - HashMapHolder<Player>::MapType const& GetPlayers(); + TC_GAME_API HashMapHolder<Player>::MapType const& GetPlayers(); template<class T> void AddObject(T* object) @@ -125,7 +105,8 @@ namespace ObjectAccessor HashMapHolder<T>::Remove(object); } - void SaveAllPlayers(); + TC_GAME_API void SaveAllPlayers(); }; #endif + diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index f45634e9684..bbd0cee2a51 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -235,6 +235,12 @@ ObjectMgr::ObjectMgr(): } } +ObjectMgr* ObjectMgr::instance() +{ + static ObjectMgr instance; + return &instance; +} + ObjectMgr::~ObjectMgr() { for (QuestMap::iterator i = _questTemplates.begin(); i != _questTemplates.end(); ++i) @@ -467,7 +473,7 @@ void ObjectMgr::LoadCreatureTemplate(Field* fields) creatureTemplate.unit_flags = fields[29].GetUInt32(); creatureTemplate.unit_flags2 = fields[30].GetUInt32(); creatureTemplate.dynamicflags = fields[31].GetUInt32(); - creatureTemplate.family = fields[32].GetUInt8(); + creatureTemplate.family = CreatureFamily(fields[32].GetUInt8()); creatureTemplate.trainer_type = fields[33].GetUInt8(); creatureTemplate.trainer_spell = fields[34].GetUInt32(); creatureTemplate.trainer_class = fields[35].GetUInt8(); @@ -481,7 +487,7 @@ void ObjectMgr::LoadCreatureTemplate(Field* fields) for (uint8 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) creatureTemplate.resistance[i] = fields[42 + i - 1].GetInt16(); - for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i = 0; i < MAX_CREATURE_SPELLS; ++i) creatureTemplate.spells[i] = fields[48 + i].GetUInt32(); creatureTemplate.PetSpellDataId = fields[56].GetUInt32(); @@ -827,7 +833,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (!displayScaleEntry) TC_LOG_ERROR("sql.sql", "Creature (Entry: %u) does not have any existing display id in Modelid1/Modelid2/Modelid3/Modelid4.", cInfo->Entry); - for (int k = 0; k < MAX_KILL_CREDIT; ++k) + for (uint8 k = 0; k < MAX_KILL_CREDIT; ++k) { if (cInfo->KillCredit[k]) { @@ -882,7 +888,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM) { TC_LOG_ERROR("sql.sql", "Creature (Entry: %u) has invalid creature family (%u) in `family`.", cInfo->Entry, cInfo->family); - const_cast<CreatureTemplate*>(cInfo)->family = 0; + const_cast<CreatureTemplate*>(cInfo)->family = CREATURE_FAMILY_NONE; } if (cInfo->InhabitType <= 0 || cInfo->InhabitType > INHABIT_ANYWHERE) @@ -914,7 +920,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) TC_LOG_ERROR("sql.sql", "Creature (Entry: %u) has non-existing PetSpellDataId (%u).", cInfo->Entry, cInfo->PetSpellDataId); } - for (uint8 j = 0; j < CREATURE_MAX_SPELLS; ++j) + for (uint8 j = 0; j < MAX_CREATURE_SPELLS; ++j) { if (cInfo->spells[j] && !sSpellMgr->GetSpellInfo(cInfo->spells[j])) { @@ -1044,8 +1050,8 @@ void ObjectMgr::LoadGameObjectAddons() { uint32 oldMSTime = getMSTime(); - // 0 1 2 - QueryResult result = WorldDatabase.Query("SELECT guid, invisibilityType, invisibilityValue FROM gameobject_addon"); + // 0 1 2 3 4 5 6 + QueryResult result = WorldDatabase.Query("SELECT guid, parent_rotation0, parent_rotation1, parent_rotation2, parent_rotation3, invisibilityType, invisibilityValue FROM gameobject_addon"); if (!result) { @@ -1060,7 +1066,7 @@ void ObjectMgr::LoadGameObjectAddons() ObjectGuid::LowType guid = fields[0].GetUInt32(); - const GameObjectData* goData = GetGOData(guid); + GameObjectData const* goData = GetGOData(guid); if (!goData) { TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) does not exist but has a record in `gameobject_addon`", guid); @@ -1068,12 +1074,13 @@ void ObjectMgr::LoadGameObjectAddons() } GameObjectAddon& gameObjectAddon = _gameObjectAddonStore[guid]; - gameObjectAddon.invisibilityType = InvisibilityType(fields[1].GetUInt8()); - gameObjectAddon.InvisibilityValue = fields[2].GetUInt32(); + gameObjectAddon.ParentRotation = G3D::Quat(fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); + gameObjectAddon.invisibilityType = InvisibilityType(fields[5].GetUInt8()); + gameObjectAddon.InvisibilityValue = fields[6].GetUInt32(); if (gameObjectAddon.invisibilityType >= TOTAL_INVISIBILITY_TYPES) { - TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) has invalid InvisibilityType in `gameobject_addon`", guid); + TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) has invalid InvisibilityType in `gameobject_addon`, disabled invisibility", guid); gameObjectAddon.invisibilityType = INVISIBILITY_GENERAL; gameObjectAddon.InvisibilityValue = 0; } @@ -1084,6 +1091,12 @@ void ObjectMgr::LoadGameObjectAddons() gameObjectAddon.InvisibilityValue = 1; } + if (!gameObjectAddon.ParentRotation.isUnit()) + { + TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) has invalid path rotation, set to default", guid); + gameObjectAddon.ParentRotation = G3D::Quat(); + } + ++count; } while (result->NextRow()); @@ -1877,10 +1890,10 @@ ObjectGuid::LowType ObjectMgr::AddGOData(uint32 entry, uint32 mapId, float x, fl data.posY = y; data.posZ = z; data.orientation = o; - data.rotation0 = rotation0; - data.rotation1 = rotation1; - data.rotation2 = rotation2; - data.rotation3 = rotation3; + data.rotation.x = rotation0; + data.rotation.y = rotation1; + data.rotation.z = rotation2; + data.rotation.w = rotation3; data.spawntimesecs = spawntimedelay; data.animprogress = 100; data.spawnMask = 1; @@ -2030,10 +2043,10 @@ void ObjectMgr::LoadGameobjects() data.posY = fields[4].GetFloat(); data.posZ = fields[5].GetFloat(); data.orientation = fields[6].GetFloat(); - data.rotation0 = fields[7].GetFloat(); - data.rotation1 = fields[8].GetFloat(); - data.rotation2 = fields[9].GetFloat(); - data.rotation3 = fields[10].GetFloat(); + data.rotation.x = fields[7].GetFloat(); + data.rotation.y = fields[8].GetFloat(); + data.rotation.z = fields[9].GetFloat(); + data.rotation.w = fields[10].GetFloat(); data.spawntimesecs = fields[11].GetInt32(); MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid); @@ -2074,15 +2087,27 @@ void ObjectMgr::LoadGameobjects() data.orientation = Position::NormalizeOrientation(data.orientation); } - if (data.rotation2 < -1.0f || data.rotation2 > 1.0f) + if (data.rotation.x < -1.0f || data.rotation.x > 1.0f) + { + TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotationX (%f) value, skip", guid, data.id, data.rotation.x); + continue; + } + + if (data.rotation.y < -1.0f || data.rotation.y > 1.0f) + { + TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotationY (%f) value, skip", guid, data.id, data.rotation.y); + continue; + } + + if (data.rotation.z < -1.0f || data.rotation.z > 1.0f) { - TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotation2 (%f) value, skip", guid, data.id, data.rotation2); + TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotationZ (%f) value, skip", guid, data.id, data.rotation.z); continue; } - if (data.rotation3 < -1.0f || data.rotation3 > 1.0f) + if (data.rotation.w < -1.0f || data.rotation.w > 1.0f) { - TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotation3 (%f) value, skip", guid, data.id, data.rotation3); + TC_LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: %u Entry: %u) with invalid rotationW (%f) value, skip", guid, data.id, data.rotation.w); continue; } @@ -2172,26 +2197,12 @@ ObjectGuid ObjectMgr::GetPlayerGUIDByName(std::string const& name) const bool ObjectMgr::GetPlayerNameByGUID(ObjectGuid guid, std::string& name) const { - // prevent DB access for online player - if (Player* player = ObjectAccessor::FindConnectedPlayer(guid)) - { - name = player->GetName(); - return true; - } - - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME); - - stmt->setUInt32(0, guid.GetCounter()); - - PreparedQueryResult result = CharacterDatabase.Query(stmt); - - if (result) - { - name = (*result)[0].GetString(); - return true; - } + CharacterInfo const* characterInfo = sWorld->GetCharacterInfo(guid); + if (!characterInfo) + return false; - return false; + name = characterInfo->Name; + return true; } uint32 ObjectMgr::GetPlayerTeamByGUID(ObjectGuid guid) const @@ -3523,6 +3534,61 @@ void ObjectMgr::LoadPlayerInfo() } } + // Load playercreate cast spell + TC_LOG_INFO("server.loading", "Loading Player Create Cast Spell Data..."); + { + uint32 oldMSTime = getMSTime(); + + QueryResult result = WorldDatabase.PQuery("SELECT raceMask, classMask, spell FROM playercreateinfo_cast_spell"); + + if (!result) + TC_LOG_ERROR("server.loading", ">> Loaded 0 player create cast spells. DB table `playercreateinfo_cast_spell` is empty."); + else + { + uint32 count = 0; + + do + { + Field* fields = result->Fetch(); + uint32 raceMask = fields[0].GetUInt32(); + uint32 classMask = fields[1].GetUInt32(); + uint32 spellId = fields[2].GetUInt32(); + + if (raceMask != 0 && !(raceMask & RACEMASK_ALL_PLAYABLE)) + { + TC_LOG_ERROR("sql.sql", "Wrong race mask %u in `playercreateinfo_cast_spell` table, ignoring.", raceMask); + continue; + } + + if (classMask != 0 && !(classMask & CLASSMASK_ALL_PLAYABLE)) + { + TC_LOG_ERROR("sql.sql", "Wrong class mask %u in `playercreateinfo_cast_spell` table, ignoring.", classMask); + continue; + } + + for (uint32 raceIndex = RACE_HUMAN; raceIndex < MAX_RACES; ++raceIndex) + { + if (raceMask == 0 || ((1 << (raceIndex - 1)) & raceMask)) + { + for (uint32 classIndex = CLASS_WARRIOR; classIndex < MAX_CLASSES; ++classIndex) + { + if (classMask == 0 || ((1 << (classIndex - 1)) & classMask)) + { + if (PlayerInfo* info = _playerInfo[raceIndex][classIndex]) + { + info->castSpells.push_back(spellId); + ++count; + } + } + } + } + } + } while (result->NextRow()); + + TC_LOG_INFO("server.loading", ">> Loaded %u player create cast spells in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + } + } + // Load playercreate actions TC_LOG_INFO("server.loading", "Loading Player Create Action Data..."); { @@ -4050,8 +4116,8 @@ void ObjectMgr::LoadQuests() // Load `quest_template_addon` // 0 1 2 3 4 5 6 7 8 result = WorldDatabase.Query("SELECT ID, MaxLevel, AllowableClasses, SourceSpellID, PrevQuestID, NextQuestID, ExclusiveGroup, RewardMailTemplateID, RewardMailDelay, " - //9 10 11 12 13 14 15 16 - "RequiredSkillID, RequiredSkillPoints, RequiredMinRepFaction, RequiredMaxRepFaction, RequiredMinRepValue, RequiredMaxRepValue, ProvidedItemCount, SpecialFlags FROM quest_template_addon"); + //9 10 11 12 13 14 15 16 17 + "RequiredSkillID, RequiredSkillPoints, RequiredMinRepFaction, RequiredMaxRepFaction, RequiredMinRepValue, RequiredMaxRepValue, ProvidedItemCount, RewardMailSenderEntry, SpecialFlags FROM quest_template_addon LEFT JOIN quest_mail_sender ON Id=QuestId"); if (!result) { @@ -4555,6 +4621,7 @@ void ObjectMgr::LoadQuests() qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player + qinfo->RewardMailSenderEntry = 0; } else if (usedMailTemplates.find(qinfo->RewardMailTemplateId) != usedMailTemplates.end()) { @@ -4563,6 +4630,7 @@ void ObjectMgr::LoadQuests() qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId, used_mt_itr->second); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player + qinfo->RewardMailSenderEntry = 0; } else usedMailTemplates[qinfo->RewardMailTemplateId] = qinfo->GetQuestId(); @@ -4709,7 +4777,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) if (tableName.empty()) return; - if (sScriptMgr->IsScriptScheduled()) // function cannot be called when scripts are in use. + if (sMapMgr->IsScriptScheduled()) // function cannot be called when scripts are in use. return; TC_LOG_INFO("server.loading", "Loading %s...", tableName.c_str()); @@ -5156,7 +5224,7 @@ void ObjectMgr::LoadSpellScriptNames() while (spellInfo) { - _spellScriptsStore.insert(SpellScriptsContainer::value_type(spellInfo->Id, GetScriptId(scriptName))); + _spellScriptsStore.insert(SpellScriptsContainer::value_type(spellInfo->Id, std::make_pair(GetScriptId(scriptName), true))); spellInfo = spellInfo->GetNextRankSpell(); } } @@ -5165,7 +5233,7 @@ void ObjectMgr::LoadSpellScriptNames() if (spellInfo->IsRanked()) TC_LOG_ERROR("sql.sql", "Scriptname: `%s` spell (Id: %d) is ranked spell. Perhaps not all ranks are assigned to this script.", scriptName.c_str(), spellId); - _spellScriptsStore.insert(SpellScriptsContainer::value_type(spellInfo->Id, GetScriptId(scriptName))); + _spellScriptsStore.insert(SpellScriptsContainer::value_type(spellInfo->Id, std::make_pair(GetScriptId(scriptName), true))); } ++count; @@ -5187,45 +5255,59 @@ void ObjectMgr::ValidateSpellScripts() uint32 count = 0; - for (SpellScriptsContainer::iterator itr = _spellScriptsStore.begin(); itr != _spellScriptsStore.end();) + for (auto spell : _spellScriptsStore) { - SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(itr->first); - std::vector<std::pair<SpellScriptLoader *, SpellScriptsContainer::iterator> > SpellScriptLoaders; - sScriptMgr->CreateSpellScriptLoaders(itr->first, SpellScriptLoaders); - itr = _spellScriptsStore.upper_bound(itr->first); + SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(spell.first); + + auto const bounds = sObjectMgr->GetSpellScriptsBounds(spell.first); - for (std::vector<std::pair<SpellScriptLoader *, SpellScriptsContainer::iterator> >::iterator sitr = SpellScriptLoaders.begin(); sitr != SpellScriptLoaders.end(); ++sitr) + for (auto itr = bounds.first; itr != bounds.second; ++itr) { - SpellScript* spellScript = sitr->first->GetSpellScript(); - AuraScript* auraScript = sitr->first->GetAuraScript(); - bool valid = true; - if (!spellScript && !auraScript) - { - TC_LOG_ERROR("scripts", "Functions GetSpellScript() and GetAuraScript() of script `%s` do not return objects - script skipped", GetScriptName(sitr->second->second).c_str()); - valid = false; - } - if (spellScript) - { - spellScript->_Init(&sitr->first->GetName(), spellEntry->Id); - spellScript->_Register(); - if (!spellScript->_Validate(spellEntry)) - valid = false; - delete spellScript; - } - if (auraScript) + if (SpellScriptLoader* spellScriptLoader = sScriptMgr->GetSpellScriptLoader(itr->second.first)) { - auraScript->_Init(&sitr->first->GetName(), spellEntry->Id); - auraScript->_Register(); - if (!auraScript->_Validate(spellEntry)) - valid = false; - delete auraScript; - } - if (!valid) - { - _spellScriptsStore.erase(sitr->second); + ++count; + + std::unique_ptr<SpellScript> spellScript(spellScriptLoader->GetSpellScript()); + std::unique_ptr<AuraScript> auraScript(spellScriptLoader->GetAuraScript()); + + if (!spellScript && !auraScript) + { + TC_LOG_ERROR("scripts", "Functions GetSpellScript() and GetAuraScript() of script `%s` do not return objects - script skipped", GetScriptName(itr->second.first).c_str()); + + itr->second.second = false; + continue; + } + + if (spellScript) + { + spellScript->_Init(&spellScriptLoader->GetName(), spellEntry->Id); + spellScript->_Register(); + + if (!spellScript->_Validate(spellEntry)) + { + itr->second.second = false; + continue; + } + } + + if (auraScript) + { + auraScript->_Init(&spellScriptLoader->GetName(), spellEntry->Id); + auraScript->_Register(); + + if (!auraScript->_Validate(spellEntry)) + { + itr->second.second = false; + continue; + } + } + + // Enable the script when all checks passed + itr->second.second = true; } + else + itr->second.second = false; } - ++count; } TC_LOG_INFO("server.loading", ">> Validated %u scripts in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -5926,14 +6008,14 @@ void ObjectMgr::LoadGraveyardZones() { uint32 oldMSTime = getMSTime(); - GraveYardStore.clear(); // need for reload case + GraveYardStore.clear(); // need for reload case - // 0 1 2 - QueryResult result = WorldDatabase.Query("SELECT id, ghost_zone, faction FROM game_graveyard_zone"); + // 0 1 2 + QueryResult result = WorldDatabase.Query("SELECT ID, GhostZone, Faction FROM graveyard_zone"); if (!result) { - TC_LOG_INFO("server.loading", ">> Loaded 0 graveyard-zone links. DB table `game_graveyard_zone` is empty."); + TC_LOG_INFO("server.loading", ">> Loaded 0 graveyard-zone links. DB table `graveyard_zone` is empty."); return; } @@ -5952,31 +6034,31 @@ void ObjectMgr::LoadGraveyardZones() WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(safeLocId); if (!entry) { - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has a record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.", safeLocId); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for non-existing graveyard (WorldSafeLocsID: %u), skipped.", safeLocId); continue; } AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(zoneId); if (!areaEntry) { - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has a record for not existing zone id (%u), skipped.", zoneId); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for non-existing Zone (ID: %u), skipped.", zoneId); continue; } if (areaEntry->zone != 0) { - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has a record for subzone id (%u) instead of zone, skipped.", zoneId); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for SubZone (ID: %u) instead of zone, skipped.", zoneId); continue; } if (team != 0 && team != HORDE && team != ALLIANCE) { - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has a record for non player faction (%u), skipped.", team); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for non player faction (%u), skipped.", team); continue; } if (!AddGraveYardLink(safeLocId, zoneId, team, false)) - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.", safeLocId, zoneId); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.", safeLocId, zoneId); } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u graveyard-zone links in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -6025,7 +6107,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float if (range.first == range.second && !map->IsBattlegroundOrArena()) { if (zoneId != 0) // zone == 0 can't be fixed, used by bliz for bugged zones - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); return GetDefaultGraveYard(team); } @@ -6051,7 +6133,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId); if (!entry) { - TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` has record for not existing graveyard (WorldSafeLocs.dbc id) %u, skipped.", data.safeLocId); + TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has record for not existing graveyard (WorldSafeLocsID %u), skipped.", data.safeLocId); continue; } @@ -6166,7 +6248,7 @@ void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool GraveYardMapBoundsNonConst range = GraveYardStore.equal_range(zoneId); if (range.first == range.second) { - //TC_LOG_ERROR("sql.sql", "Table `game_graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); + //TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); return; } @@ -6474,7 +6556,7 @@ uint32 ObjectMgr::GenerateAuctionID() { if (_auctionId >= 0xFFFFFFFE) { - TC_LOG_ERROR("misc", "Auctions ids overflow!! Can't continue, shutting down server. "); + TC_LOG_ERROR("misc", "Auctions ids overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info. "); World::StopNow(ERROR_EXIT_CODE); } return _auctionId++; @@ -6484,7 +6566,7 @@ uint64 ObjectMgr::GenerateEquipmentSetGuid() { if (_equipmentSetGuid >= uint64(0xFFFFFFFFFFFFFFFELL)) { - TC_LOG_ERROR("misc", "EquipmentSet guid overflow!! Can't continue, shutting down server. "); + TC_LOG_ERROR("misc", "EquipmentSet guid overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info. "); World::StopNow(ERROR_EXIT_CODE); } return _equipmentSetGuid++; @@ -6494,7 +6576,7 @@ uint32 ObjectMgr::GenerateMailID() { if (_mailId >= 0xFFFFFFFE) { - TC_LOG_ERROR("misc", "Mail ids overflow!! Can't continue, shutting down server. "); + TC_LOG_ERROR("misc", "Mail ids overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info. "); World::StopNow(ERROR_EXIT_CODE); } return _mailId++; @@ -6502,14 +6584,19 @@ uint32 ObjectMgr::GenerateMailID() uint32 ObjectMgr::GeneratePetNumber() { - return ++_hiPetNumber; + if (_hiPetNumber >= 0xFFFFFFFE) + { + TC_LOG_ERROR("misc", "_hiPetNumber Id overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info."); + World::StopNow(ERROR_EXIT_CODE); + } + return _hiPetNumber++; } uint32 ObjectMgr::GenerateCreatureSpawnId() { if (_creatureSpawnId >= uint32(0xFFFFFF)) { - TC_LOG_ERROR("misc", "Creature spawn id overflow!! Can't continue, shutting down server. "); + TC_LOG_ERROR("misc", "Creature spawn id overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info."); World::StopNow(ERROR_EXIT_CODE); } return _creatureSpawnId++; @@ -6519,7 +6606,7 @@ uint32 ObjectMgr::GenerateGameObjectSpawnId() { if (_gameObjectSpawnId >= uint32(0xFFFFFF)) { - TC_LOG_ERROR("misc", "Creature spawn id overflow!! Can't continue, shutting down server. "); + TC_LOG_ERROR("misc", "Creature spawn id overflow!! Can't continue, shutting down server. Search on forum for TCE00007 for more info. "); World::StopNow(ERROR_EXIT_CODE); } return _gameObjectSpawnId++; @@ -7614,7 +7701,7 @@ ResponseCodes ObjectMgr::CheckPlayerName(std::string const& name, LocaleConstant if (wname[i] == wname[i-1] && wname[i] == wname[i-2]) return CHAR_NAME_THREE_CONSECUTIVE; - return ValidateName(name, locale); + return ValidateName(wname, locale); } bool ObjectMgr::IsValidCharterName(const std::string& name) @@ -7652,7 +7739,7 @@ PetNameInvalidReason ObjectMgr::CheckPetName(const std::string& name, LocaleCons if (!isValidString(wname, strictMask, false)) return PET_NAME_MIXED_LANGUAGES; - switch (ValidateName(name, locale)) + switch (ValidateName(wname, locale)) { case CHAR_NAME_PROFANE: return PET_NAME_PROFANE; @@ -7738,7 +7825,7 @@ bool ObjectMgr::LoadTrinityStrings() QueryResult result = WorldDatabase.Query("SELECT entry, content_default, content_loc1, content_loc2, content_loc3, content_loc4, content_loc5, content_loc6, content_loc7, content_loc8 FROM trinity_string"); if (!result) { - TC_LOG_ERROR("server.loading", ">> Loaded 0 trinity strings. DB table `trinity_string` is empty."); + TC_LOG_ERROR("server.loading", ">> Loaded 0 trinity strings. DB table `trinity_string` is empty. You have imported an incorrect database for more info search for TCE00003 on forum."); return false; } @@ -8560,6 +8647,8 @@ void ObjectMgr::LoadScriptNames() { uint32 oldMSTime = getMSTime(); + // We insert an empty placeholder here so we can use the + // script id 0 as dummy for "no script found". _scriptNamesStore.emplace_back(""); QueryResult result = WorldDatabase.Query( @@ -8601,18 +8690,18 @@ void ObjectMgr::LoadScriptNames() std::sort(_scriptNamesStore.begin(), _scriptNamesStore.end()); -#ifdef SCRIPTS - for (size_t i = 1; i < _scriptNamesStore.size(); ++i) - UnusedScriptNames.push_back(_scriptNamesStore[i]); -#endif - TC_LOG_INFO("server.loading", ">> Loaded " SZFMTD " ScriptNames in %u ms", _scriptNamesStore.size(), GetMSTimeDiffToNow(oldMSTime)); } +ObjectMgr::ScriptNameContainer const& ObjectMgr::GetAllScriptNames() const +{ + return _scriptNamesStore; +} + std::string const& ObjectMgr::GetScriptName(uint32 id) const { static std::string const empty = ""; - return id < _scriptNamesStore.size() ? _scriptNamesStore[id] : empty; + return (id < _scriptNamesStore.size()) ? _scriptNamesStore[id] : empty; } diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index ae1258713f5..f06c9faf58b 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -28,7 +28,7 @@ #include "TemporarySummon.h" #include "Corpse.h" #include "QuestDef.h" -#include "ItemPrototype.h" +#include "ItemTemplate.h" #include "NPCHandler.h" #include "DatabaseEnv.h" #include "Mail.h" @@ -370,17 +370,17 @@ struct ScriptInfo typedef std::multimap<uint32, ScriptInfo> ScriptMap; typedef std::map<uint32, ScriptMap > ScriptMapMap; -typedef std::multimap<uint32, uint32> SpellScriptsContainer; +typedef std::multimap<uint32 /*spell id*/, std::pair<uint32 /*script id*/, bool /*enabled*/>> SpellScriptsContainer; typedef std::pair<SpellScriptsContainer::iterator, SpellScriptsContainer::iterator> SpellScriptsBounds; -extern ScriptMapMap sSpellScripts; -extern ScriptMapMap sEventScripts; -extern ScriptMapMap sWaypointScripts; +TC_GAME_API extern ScriptMapMap sSpellScripts; +TC_GAME_API extern ScriptMapMap sEventScripts; +TC_GAME_API extern ScriptMapMap sWaypointScripts; std::string GetScriptsTableNameByType(ScriptsType type); ScriptMapMap* GetScriptsMapByType(ScriptsType type); std::string GetScriptCommandName(ScriptCommands command); -struct SpellClickInfo +struct TC_GAME_API SpellClickInfo { uint32 spellId; uint8 castFlags; @@ -637,7 +637,7 @@ SkillRangeType GetSkillRangeType(SkillRaceClassInfoEntry const* rcEntry); #define MAX_PET_NAME 12 // max allowed by client name length #define MAX_CHARTER_NAME 24 // max allowed by client name length -bool normalizePlayerName(std::string& name); +TC_GAME_API bool normalizePlayerName(std::string& name); struct LanguageDesc { @@ -646,7 +646,7 @@ struct LanguageDesc uint32 skill_id; }; -extern LanguageDesc lang_description[LANGUAGES_COUNT]; +TC_GAME_API extern LanguageDesc lang_description[LANGUAGES_COUNT]; LanguageDesc const* GetLanguageDescByID(uint32 lang); enum EncounterCreditType @@ -671,7 +671,7 @@ typedef std::unordered_map<uint32, DungeonEncounterList> DungeonEncounterContain class PlayerDumpReader; -class ObjectMgr +class TC_GAME_API ObjectMgr { friend class PlayerDumpReader; @@ -680,11 +680,13 @@ class ObjectMgr ~ObjectMgr(); public: - static ObjectMgr* instance() - { - static ObjectMgr instance; - return &instance; - } + ObjectMgr(ObjectMgr const&) = delete; + ObjectMgr(ObjectMgr&&) = delete; + + ObjectMgr& operator= (ObjectMgr const&) = delete; + ObjectMgr& operator= (ObjectMgr&&) = delete; + + static ObjectMgr* instance(); typedef std::unordered_map<uint32, Item*> ItemMap; @@ -1270,6 +1272,7 @@ class ObjectMgr bool IsVendorItemValid(uint32 vendor_entry, uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost, Player* player = NULL, std::set<uint32>* skip_vendors = NULL, uint32 ORnpcflag = 0) const; void LoadScriptNames(); + ScriptNameContainer const& GetAllScriptNames() const; std::string const& GetScriptName(uint32 id) const; uint32 GetScriptId(std::string const& name); diff --git a/src/server/game/Grids/GridReference.h b/src/server/game/Grids/GridReference.h index b1f2e92a840..f5766382822 100644 --- a/src/server/game/Grids/GridReference.h +++ b/src/server/game/Grids/GridReference.h @@ -28,18 +28,18 @@ template<class OBJECT> class GridReference : public Reference<GridRefManager<OBJECT>, OBJECT> { protected: - void targetObjectBuildLink() + void targetObjectBuildLink() override { // called from link() this->getTarget()->insertFirst(this); this->getTarget()->incSize(); } - void targetObjectDestroyLink() + void targetObjectDestroyLink() override { // called from unlink() if (this->isValid()) this->getTarget()->decSize(); } - void sourceObjectDestroyLink() + void sourceObjectDestroyLink() override { // called from invalidate() this->getTarget()->decSize(); diff --git a/src/server/game/Grids/GridStates.h b/src/server/game/Grids/GridStates.h index 9420bef4b9d..b567da43b69 100644 --- a/src/server/game/Grids/GridStates.h +++ b/src/server/game/Grids/GridStates.h @@ -24,32 +24,32 @@ class Map; -class GridState +class TC_GAME_API GridState { public: virtual ~GridState() { }; virtual void Update(Map &, NGridType&, GridInfo &, uint32 t_diff) const = 0; }; -class InvalidState : public GridState +class TC_GAME_API InvalidState : public GridState { public: void Update(Map &, NGridType &, GridInfo &, uint32 t_diff) const override; }; -class ActiveState : public GridState +class TC_GAME_API ActiveState : public GridState { public: void Update(Map &, NGridType &, GridInfo &, uint32 t_diff) const override; }; -class IdleState : public GridState +class TC_GAME_API IdleState : public GridState { public: void Update(Map &, NGridType &, GridInfo &, uint32 t_diff) const override; }; -class RemovalState : public GridState +class TC_GAME_API RemovalState : public GridState { public: void Update(Map &, NGridType &, GridInfo &, uint32 t_diff) const override; diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.cpp b/src/server/game/Grids/Notifiers/GridNotifiers.cpp index 571d56b618e..2cdbdca4e4f 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.cpp +++ b/src/server/game/Grids/Notifiers/GridNotifiers.cpp @@ -131,7 +131,7 @@ inline void CreatureUnitRelocationWorker(Creature* c, Unit* u) if (!u->IsAlive() || !c->IsAlive() || c == u || u->IsInFlight()) return; - if ((c->HasReactState(REACT_AGGRESSIVE) || c->IsTrigger()) && !c->HasUnitState(UNIT_STATE_SIGHTLESS)) + if (!c->HasUnitState(UNIT_STATE_SIGHTLESS)) { if (c->IsAIEnabled && c->CanSeeOrDetect(u, false, true)) c->AI()->MoveInLineOfSight_Safe(u); diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.h b/src/server/game/Grids/Notifiers/GridNotifiers.h index 6edeadf6b94..5283805c59d 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.h +++ b/src/server/game/Grids/Notifiers/GridNotifiers.h @@ -38,7 +38,7 @@ class Player; namespace Trinity { - struct VisibleNotifier + struct TC_GAME_API VisibleNotifier { Player &i_player; UpdateData i_data; @@ -61,7 +61,7 @@ namespace Trinity void Visit(DynamicObjectMapType &); }; - struct PlayerRelocationNotifier : public VisibleNotifier + struct TC_GAME_API PlayerRelocationNotifier : public VisibleNotifier { PlayerRelocationNotifier(Player &player) : VisibleNotifier(player) { } @@ -70,7 +70,7 @@ namespace Trinity void Visit(PlayerMapType &); }; - struct CreatureRelocationNotifier + struct TC_GAME_API CreatureRelocationNotifier { Creature &i_creature; CreatureRelocationNotifier(Creature &c) : i_creature(c) { } @@ -79,7 +79,7 @@ namespace Trinity void Visit(PlayerMapType &); }; - struct DelayedUnitRelocation + struct TC_GAME_API DelayedUnitRelocation { Map &i_map; Cell &cell; @@ -92,7 +92,7 @@ namespace Trinity void Visit(PlayerMapType &); }; - struct AIRelocationNotifier + struct TC_GAME_API AIRelocationNotifier { Unit &i_unit; bool isCreature; @@ -120,7 +120,7 @@ namespace Trinity void Visit(CorpseMapType &m) { updateObjects<Corpse>(m); } }; - struct MessageDistDeliverer + struct TC_GAME_API MessageDistDeliverer { WorldObject* i_source; WorldPacket* i_message; @@ -566,7 +566,7 @@ namespace Trinity // WorldObject check classes - class AnyDeadUnitObjectInRangeCheck + class TC_GAME_API AnyDeadUnitObjectInRangeCheck { public: AnyDeadUnitObjectInRangeCheck(Unit* searchObj, float range) : i_searchObj(searchObj), i_range(range) { } @@ -579,7 +579,7 @@ namespace Trinity float i_range; }; - class AnyDeadUnitSpellTargetInRangeCheck : public AnyDeadUnitObjectInRangeCheck + class TC_GAME_API AnyDeadUnitSpellTargetInRangeCheck : public AnyDeadUnitObjectInRangeCheck { public: AnyDeadUnitSpellTargetInRangeCheck(Unit* searchObj, float range, SpellInfo const* spellInfo, SpellTargetCheckTypes check) @@ -620,6 +620,9 @@ namespace Trinity if (go->GetGOInfo()->spellFocus.focusId != i_focusId) return false; + if (!go->isSpawned()) + return false; + float dist = go->GetGOInfo()->spellFocus.dist / 2.f; return go->IsWithinDistInMap(i_unit, dist); @@ -1237,7 +1240,7 @@ namespace Trinity AllGameObjectsWithEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator() (GameObject* go) { - if (go->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(go, m_fRange, false)) + if ((!m_uiEntry || go->GetEntry() == m_uiEntry) && m_pObject->IsWithinDist(go, m_fRange, false)) return true; return false; @@ -1254,7 +1257,7 @@ namespace Trinity AllCreaturesOfEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator() (Unit* unit) { - if (unit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(unit, m_fRange, false)) + if ((!m_uiEntry || unit->GetEntry() == m_uiEntry) && m_pObject->IsWithinDist(unit, m_fRange, false)) return true; return false; diff --git a/src/server/game/Grids/ObjectGridLoader.h b/src/server/game/Grids/ObjectGridLoader.h index 9dc4c7e048b..f2893da609e 100644 --- a/src/server/game/Grids/ObjectGridLoader.h +++ b/src/server/game/Grids/ObjectGridLoader.h @@ -27,7 +27,7 @@ class ObjectWorldLoader; -class ObjectGridLoader +class TC_GAME_API ObjectGridLoader { friend class ObjectWorldLoader; @@ -55,7 +55,7 @@ class ObjectGridLoader }; //Stop the creatures before unloading the NGrid -class ObjectGridStoper +class TC_GAME_API ObjectGridStoper { public: void Visit(CreatureMapType &m); @@ -63,7 +63,7 @@ class ObjectGridStoper }; //Move the foreign creatures back to respawn positions before unloading the NGrid -class ObjectGridEvacuator +class TC_GAME_API ObjectGridEvacuator { public: void Visit(CreatureMapType &m); diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index 42fd9b582e8..18b8119246f 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -158,7 +158,7 @@ struct InstanceGroupBind /** request member stats checken **/ /// @todo uninvite people that not accepted invite -class Group +class TC_GAME_API Group { public: struct MemberSlot diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index 0fd2e7c7095..a5aa432aadc 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -92,6 +92,12 @@ ObjectGuid::LowType GroupMgr::GenerateGroupId() return NextGroupId++; } +GroupMgr* GroupMgr::instance() +{ + static GroupMgr instance; + return &instance; +} + Group* GroupMgr::GetGroupByGUID(ObjectGuid::LowType groupId) const { GroupContainer::const_iterator itr = GroupStore.find(groupId); diff --git a/src/server/game/Groups/GroupMgr.h b/src/server/game/Groups/GroupMgr.h index 9afdddd0f18..14ff3519aa6 100644 --- a/src/server/game/Groups/GroupMgr.h +++ b/src/server/game/Groups/GroupMgr.h @@ -20,18 +20,14 @@ #include "Group.h" -class GroupMgr +class TC_GAME_API GroupMgr { private: GroupMgr(); ~GroupMgr(); public: - static GroupMgr* instance() - { - static GroupMgr instance; - return &instance; - } + static GroupMgr* instance(); typedef std::map<ObjectGuid::LowType, Group*> GroupContainer; typedef std::vector<Group*> GroupDbContainer; diff --git a/src/server/game/Groups/GroupReference.h b/src/server/game/Groups/GroupReference.h index 4718dda1832..6e7373de7d7 100644 --- a/src/server/game/Groups/GroupReference.h +++ b/src/server/game/Groups/GroupReference.h @@ -24,7 +24,7 @@ class Group; class Player; -class GroupReference : public Reference<Group, Player> +class TC_GAME_API GroupReference : public Reference<Group, Player> { protected: uint8 iSubGroup; diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index 87494e78a28..121afc014ce 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -1443,17 +1443,17 @@ void Guild::HandleSetBankTabInfo(WorldSession* session, uint8 tabId, std::string _BroadcastEvent(GE_BANK_TAB_UPDATED, ObjectGuid::Empty, aux, name.c_str(), icon.c_str()); } -void Guild::HandleSetMemberNote(WorldSession* session, std::string const& name, std::string const& note, bool isPublic) +void Guild::HandleSetMemberNote(WorldSession* session, std::string const& name, std::string const& note, bool officer) { // Player must have rights to set public/officer note - if (!_HasRankRight(session->GetPlayer(), isPublic ? GR_RIGHT_EPNOTE : GR_RIGHT_EOFFNOTE)) + if (!_HasRankRight(session->GetPlayer(), officer ? GR_RIGHT_EOFFNOTE : GR_RIGHT_EPNOTE)) SendCommandResult(session, GUILD_COMMAND_PUBLIC_NOTE, ERR_GUILD_PERMISSIONS); else if (Member* member = GetMember(name)) { - if (isPublic) - member->SetPublicNote(note); - else + if (officer) member->SetOfficerNote(note); + else + member->SetPublicNote(note); HandleRoster(session); } diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 2bc57a70671..e25a3201957 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -223,7 +223,7 @@ enum GuildMemberFlags }; // Emblem info -class EmblemInfo +class TC_GAME_API EmblemInfo { public: EmblemInfo() : m_style(0), m_color(0), m_borderStyle(0), m_borderColor(0), m_backgroundColor(0) { } @@ -279,7 +279,7 @@ typedef std::vector <GuildBankRightsAndSlots> GuildBankRightsAndSlotsVec; typedef std::set <uint8> SlotIds; -class Guild +class TC_GAME_API Guild { private: // Class representing guild member diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index 2d4fb849fb5..a4d245cbc9b 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -79,6 +79,12 @@ std::string GuildMgr::GetGuildNameById(ObjectGuid::LowType guildId) const return ""; } +GuildMgr* GuildMgr::instance() +{ + static GuildMgr instance; + return &instance; +} + Guild* GuildMgr::GetGuildByLeader(ObjectGuid guid) const { for (GuildContainer::const_iterator itr = GuildStore.begin(); itr != GuildStore.end(); ++itr) diff --git a/src/server/game/Guilds/GuildMgr.h b/src/server/game/Guilds/GuildMgr.h index a97a59cafe0..ad2555c2e71 100644 --- a/src/server/game/Guilds/GuildMgr.h +++ b/src/server/game/Guilds/GuildMgr.h @@ -20,18 +20,14 @@ #include "Guild.h" -class GuildMgr +class TC_GAME_API GuildMgr { private: GuildMgr(); ~GuildMgr(); public: - static GuildMgr* instance() - { - static GuildMgr instance; - return &instance; - } + static GuildMgr* instance(); Guild* GetGuildByLeader(ObjectGuid guid) const; Guild* GetGuildById(ObjectGuid::LowType guildId) const; diff --git a/src/server/game/Handlers/AddonHandler.cpp b/src/server/game/Handlers/AddonHandler.cpp index ad44e0993e4..c72fc08982c 100644 --- a/src/server/game/Handlers/AddonHandler.cpp +++ b/src/server/game/Handlers/AddonHandler.cpp @@ -21,6 +21,12 @@ #include "Opcodes.h" #include "Log.h" +AddonHandler* AddonHandler::instance() +{ + static AddonHandler instance; + return &instance; +} + bool AddonHandler::BuildAddonPacket(WorldPacket* source, WorldPacket* target) { ByteBuffer AddOnPacked; diff --git a/src/server/game/Handlers/AddonHandler.h b/src/server/game/Handlers/AddonHandler.h index 1e8081e0913..0113695895a 100644 --- a/src/server/game/Handlers/AddonHandler.h +++ b/src/server/game/Handlers/AddonHandler.h @@ -26,11 +26,7 @@ class AddonHandler { public: - static AddonHandler* instance() - { - static AddonHandler instance; - return &instance; - } + static AddonHandler* instance(); bool BuildAddonPacket(WorldPacket* Source, WorldPacket* Target); diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index e91da35c06b..55bfb93c1c4 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -777,7 +777,7 @@ void WorldSession::HandleReportPvPAFK(WorldPacket& recvData) if (!reportedPlayer) { - TC_LOG_DEBUG("bg.battleground", "WorldSession::HandleReportPvPAFK: player not found"); + TC_LOG_INFO("bg.reportpvpafk", "WorldSession::HandleReportPvPAFK: %s [IP: %s] reported %s [IP: %s]", _player->GetName().c_str(), _player->GetSession()->GetRemoteAddress().c_str(), reportedPlayer->GetName().c_str(), reportedPlayer->GetSession()->GetRemoteAddress().c_str()); return; } diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index 540eeba0752..1a654335714 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -700,7 +700,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) InstancePlayerBind* instanceBind = player->GetBoundInstance(mapId, Difficulty(difficulty), toggleExtend == 1); // include expired instances if we are toggling extend on if (!instanceBind || !instanceBind->save || !instanceBind->perm) return; - + BindExtensionState newState; if (!toggleExtend || instanceBind->extendState == EXTEND_STATE_EXPIRED) newState = EXTEND_STATE_NORMAL; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index e0d790312d2..812a828ddce 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -45,6 +45,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "Metric.h" class LoginQueryHolder : public SQLQueryHolder @@ -228,11 +229,11 @@ void WorldSession::HandleCharEnum(PreparedQueryResult result) if (Player::BuildEnumData(result, &data)) { // Do not allow banned characters to log in - if (!(*result)[20].GetUInt32()) + if (!(*result)[23].GetUInt32()) _legitCharacters.insert(guid); if (!sWorld->HasCharacterInfo(guid)) // This can happen if characters are inserted into the database manually. Core hasn't loaded name data yet. - sWorld->AddCharacterInfo(guid, GetAccountId(), (*result)[1].GetString(), (*result)[4].GetUInt8(), (*result)[2].GetUInt8(), (*result)[3].GetUInt8(), (*result)[7].GetUInt8()); + sWorld->AddCharacterInfo(guid, GetAccountId(), (*result)[1].GetString(), (*result)[4].GetUInt8(), (*result)[2].GetUInt8(), (*result)[3].GetUInt8(), (*result)[10].GetUInt8()); ++num; } } @@ -627,13 +628,13 @@ void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, Characte PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM); stmt->setUInt32(0, GetAccountId()); - stmt->setUInt32(1, realmID); + stmt->setUInt32(1, realm.Id.Realm); trans->Append(stmt); stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS); stmt->setUInt32(0, createInfo->CharCount); stmt->setUInt32(1, GetAccountId()); - stmt->setUInt32(2, realmID); + stmt->setUInt32(2, realm.Id.Realm); trans->Append(stmt); LoginDatabase.CommitTransaction(trans); @@ -642,7 +643,7 @@ void WorldSession::HandleCharCreateCallback(PreparedQueryResult result, Characte TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Create Character:[%s] (GUID: %u)", GetAccountId(), GetRemoteAddress().c_str(), createInfo->Name.c_str(), newChar.GetGUID().GetCounter()); sScriptMgr->OnPlayerCreate(&newChar); - sWorld->AddCharacterInfo(newChar.GetGUID(), GetAccountId(), newChar.GetName(), newChar.GetByteValue(PLAYER_BYTES_3, 0), newChar.getRace(), newChar.getClass(), newChar.getLevel()); + sWorld->AddCharacterInfo(newChar.GetGUID(), GetAccountId(), newChar.GetName(), newChar.GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER), newChar.getRace(), newChar.getClass(), newChar.getLevel()); newChar.CleanupsBeforeDelete(); delete createInfo; @@ -686,17 +687,17 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData) return; } - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DATA_BY_GUID); - stmt->setUInt32(0, guid.GetCounter()); - - if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) + CharacterInfo const* characterInfo = sWorld->GetCharacterInfo(guid); + if (!characterInfo) { - Field* fields = result->Fetch(); - accountId = fields[0].GetUInt32(); - name = fields[1].GetString(); - level = fields[2].GetUInt8(); + sScriptMgr->OnPlayerFailedDelete(guid, initAccountId); + return; } + accountId = characterInfo->AccountId; + name = characterInfo->Name; + level = characterInfo->Level; + // prevent deleting other players' characters using cheating tools if (accountId != initAccountId) { @@ -969,8 +970,14 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) bool firstLogin = pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST); if (firstLogin) + { pCurrChar->RemoveAtLoginFlag(AT_LOGIN_FIRST); + PlayerInfo const* info = sObjectMgr->GetPlayerInfo(pCurrChar->getRace(), pCurrChar->getClass()); + for (uint32 spellId : info->castSpells) + pCurrChar->CastSpell(pCurrChar, spellId, true); + } + // show time before shutdown if shutdown planned. if (sWorld->IsShuttingDown()) sWorld->ShutdownMsg(true, pCurrChar); @@ -995,6 +1002,8 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) sScriptMgr->OnPlayerLogin(pCurrChar, firstLogin); + TC_METRIC_EVENT("player_events", "Login", pCurrChar->GetName()); + delete holder; } @@ -1242,20 +1251,25 @@ void WorldSession::HandleAlterAppearance(WorldPacket& recvData) BarberShopStyleEntry const* bs_hair = sBarberShopStyleStore.LookupEntry(Hair); - if (!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->GetByteValue(PLAYER_BYTES_3, 0)) + if (!bs_hair || bs_hair->type != 0 || bs_hair->race != _player->getRace() || bs_hair->gender != _player->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER)) return; BarberShopStyleEntry const* bs_facialHair = sBarberShopStyleStore.LookupEntry(FacialHair); - if (!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->GetByteValue(PLAYER_BYTES_3, 0)) + if (!bs_facialHair || bs_facialHair->type != 2 || bs_facialHair->race != _player->getRace() || bs_facialHair->gender != _player->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER)) return; BarberShopStyleEntry const* bs_skinColor = sBarberShopStyleStore.LookupEntry(SkinColor); - if (bs_skinColor && (bs_skinColor->type != 3 || bs_skinColor->race != _player->getRace() || bs_skinColor->gender != _player->GetByteValue(PLAYER_BYTES_3, 0))) + if (bs_skinColor && (bs_skinColor->type != 3 || bs_skinColor->race != _player->getRace() || bs_skinColor->gender != _player->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER))) return; - if (!Player::ValidateAppearance(_player->getRace(), _player->getClass(), _player->GetByteValue(PLAYER_BYTES_3, 0), bs_hair->hair_id, Color, _player->GetByteValue(PLAYER_BYTES, 1), bs_facialHair->hair_id, bs_skinColor ? bs_skinColor->hair_id : _player->GetByteValue(PLAYER_BYTES, 0))) + if (!Player::ValidateAppearance(_player->getRace(), _player->getClass(), _player->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER), + bs_hair->hair_id, + Color, + _player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID), + bs_facialHair->hair_id, + bs_skinColor ? bs_skinColor->hair_id : _player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID))) return; GameObject* go = _player->FindNearestGameObjectOfType(GAMEOBJECT_TYPE_BARBER_CHAIR, 5.0f); @@ -1265,7 +1279,7 @@ void WorldSession::HandleAlterAppearance(WorldPacket& recvData) return; } - if (_player->getStandState() != UNIT_STAND_STATE_SIT_LOW_CHAIR + go->GetGOInfo()->barberChair.chairheight) + if (_player->GetStandState() != UNIT_STAND_STATE_SIT_LOW_CHAIR + go->GetGOInfo()->barberChair.chairheight) { SendBarberShopResult(BARBER_SHOP_RESULT_NOT_ON_CHAIR); return; @@ -1287,11 +1301,11 @@ void WorldSession::HandleAlterAppearance(WorldPacket& recvData) _player->ModifyMoney(-int32(cost)); // it isn't free _player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER, cost); - _player->SetByteValue(PLAYER_BYTES, 2, uint8(bs_hair->hair_id)); - _player->SetByteValue(PLAYER_BYTES, 3, uint8(Color)); - _player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id)); + _player->SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID, uint8(bs_hair->hair_id)); + _player->SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID, uint8(Color)); + _player->SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE, uint8(bs_facialHair->hair_id)); if (bs_skinColor) - _player->SetByteValue(PLAYER_BYTES, 0, uint8(bs_skinColor->hair_id)); + _player->SetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID, uint8(bs_skinColor->hair_id)); _player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1); @@ -1356,6 +1370,7 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) uint8 plrRace = fields[0].GetUInt8(); uint8 plrClass = fields[1].GetUInt8(); uint8 plrGender = fields[2].GetUInt8(); + std::string oldName = fields[4].GetString(); if (!Player::ValidateAppearance(plrRace, plrClass, plrGender, customizeInfo.HairStyle, customizeInfo.HairColor, customizeInfo.Face, customizeInfo.FacialHair, customizeInfo.Skin, true)) { @@ -1384,6 +1399,13 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) return; } + // prevent character rename + if (sWorld->getBoolConfig(CONFIG_PREVENT_RENAME_CUSTOMIZATION) && (customizeInfo.Name != oldName)) + { + SendCharCustomize(CHAR_NAME_FAILURE, customizeInfo); + return; + } + // prevent character rename to invalid name if (!normalizePlayerName(customizeInfo.Name)) { @@ -1415,17 +1437,6 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) } } - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_NAME); - stmt->setUInt32(0, customizeInfo.Guid.GetCounter()); - result = CharacterDatabase.Query(stmt); - - if (result) - { - std::string oldname = result->Fetch()[0].GetString(); - TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s), Character[%s] (%s) Customized to: %s", - GetAccountId(), GetRemoteAddress().c_str(), oldname.c_str(), customizeInfo.Guid.ToString().c_str(), customizeInfo.Name.c_str()); - } - SQLTransaction trans = CharacterDatabase.BeginTransaction(); Player::Customize(&customizeInfo, trans); @@ -1447,6 +1458,9 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) sWorld->UpdateCharacterInfo(customizeInfo.Guid, customizeInfo.Name, customizeInfo.Gender); SendCharCustomize(RESPONSE_SUCCESS, customizeInfo); + + TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s), Character[%s] (%s) Customized to: %s", + GetAccountId(), GetRemoteAddress().c_str(), oldName.c_str(), customizeInfo.Guid.ToString().c_str(), customizeInfo.Name.c_str()); } void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) @@ -1600,6 +1614,7 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) return; } + std::string oldName = nameData->Name; uint8 oldRace = nameData->Race; uint8 playerClass = nameData->Class; uint8 level = nameData->Level; @@ -1642,6 +1657,13 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) } } + // prevent character rename + if (sWorld->getBoolConfig(CONFIG_PREVENT_RENAME_CUSTOMIZATION) && (factionChangeInfo.Name != oldName)) + { + SendCharFactionChange(CHAR_NAME_FAILURE, factionChangeInfo); + return; + } + // prevent character rename to invalid name if (!normalizePlayerName(factionChangeInfo.Name)) { diff --git a/src/server/game/Handlers/ChatHandler.cpp b/src/server/game/Handlers/ChatHandler.cpp index 346adf6f091..2d94d423142 100644 --- a/src/server/game/Handlers/ChatHandler.cpp +++ b/src/server/game/Handlers/ChatHandler.cpp @@ -239,8 +239,6 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) switch (type) { case CHAT_MSG_SAY: - case CHAT_MSG_EMOTE: - case CHAT_MSG_YELL: { // Prevent cheating if (!sender->IsAlive()) @@ -252,13 +250,39 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) return; } - if (type == CHAT_MSG_SAY) - sender->Say(msg, Language(lang)); - else if (type == CHAT_MSG_EMOTE) - sender->TextEmote(msg); - else if (type == CHAT_MSG_YELL) - sender->Yell(msg, Language(lang)); - } break; + sender->Say(msg, Language(lang)); + break; + } + case CHAT_MSG_EMOTE: + { + // Prevent cheating + if (!sender->IsAlive()) + return; + + if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_EMOTE_LEVEL_REQ)) + { + SendNotification(GetTrinityString(LANG_SAY_REQ), sWorld->getIntConfig(CONFIG_CHAT_EMOTE_LEVEL_REQ)); + return; + } + + sender->TextEmote(msg); + break; + } + case CHAT_MSG_YELL: + { + // Prevent cheating + if (!sender->IsAlive()) + return; + + if (sender->getLevel() < sWorld->getIntConfig(CONFIG_CHAT_YELL_LEVEL_REQ)) + { + SendNotification(GetTrinityString(LANG_SAY_REQ), sWorld->getIntConfig(CONFIG_CHAT_YELL_LEVEL_REQ)); + return; + } + + sender->Yell(msg, Language(lang)); + break; + } case CHAT_MSG_WHISPER: { if (!normalizePlayerName(to)) @@ -298,7 +322,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sender->AddWhisperWhiteList(receiver->GetGUID()); GetPlayer()->Whisper(msg, Language(lang), receiver); - } break; + break; + } case CHAT_MSG_PARTY: case CHAT_MSG_PARTY_LEADER: { @@ -319,7 +344,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); - } break; + break; + } case CHAT_MSG_GUILD: { if (GetPlayer()->GetGuildId()) @@ -331,7 +357,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) guild->BroadcastToGuild(this, false, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); } } - } break; + break; + } case CHAT_MSG_OFFICER: { if (GetPlayer()->GetGuildId()) @@ -343,7 +370,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) guild->BroadcastToGuild(this, true, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); } } - } break; + break; + } case CHAT_MSG_RAID: { // if player is in battleground, he cannot say to battleground members by /ra @@ -360,7 +388,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID, Language(lang), sender, NULL, msg); group->BroadcastPacket(&data, false); - } break; + break; + } case CHAT_MSG_RAID_LEADER: { // if player is in battleground, he cannot say to battleground members by /ra @@ -377,7 +406,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_LEADER, Language(lang), sender, NULL, msg); group->BroadcastPacket(&data, false); - } break; + break; + } case CHAT_MSG_RAID_WARNING: { Group* group = GetPlayer()->GetGroup(); @@ -390,7 +420,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) //in battleground, raid warning is sent only to players in battleground - code is ok ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, NULL, msg); group->BroadcastPacket(&data, false); - } break; + break; + } case CHAT_MSG_BATTLEGROUND: { //battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() @@ -403,7 +434,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND, Language(lang), sender, NULL, msg); group->BroadcastPacket(&data, false); - } break; + break; + } case CHAT_MSG_BATTLEGROUND_LEADER: { // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() @@ -416,7 +448,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND_LEADER, Language(lang), sender, NULL, msg);; group->BroadcastPacket(&data, false); - } break; + break; + } case CHAT_MSG_CHANNEL: { if (!HasPermission(rbac::RBAC_PERM_SKIP_CHECK_CHAT_CHANNEL_REQ)) @@ -436,7 +469,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) chn->Say(sender->GetGUID(), msg.c_str(), lang); } } - } break; + break; + } case CHAT_MSG_AFK: { if (!sender->IsInCombat()) diff --git a/src/server/game/Handlers/GroupHandler.cpp b/src/server/game/Handlers/GroupHandler.cpp index 84cbb86345d..5ea81718a5d 100644 --- a/src/server/game/Handlers/GroupHandler.cpp +++ b/src/server/game/Handlers/GroupHandler.cpp @@ -82,6 +82,13 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) return; } + // player trying to invite himself (most likely cheating) + if (player == GetPlayer()) + { + SendPartyResult(PARTY_OP_INVITE, membername, ERR_BAD_PLAYER_NAME_S); + return; + } + // restrict invite to GMs if (!sWorld->getBoolConfig(CONFIG_ALLOW_GM_GROUP) && !GetPlayer()->IsGameMaster() && player->IsGameMaster()) { @@ -113,6 +120,12 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) return; } + if (!player->GetSocial()->HasFriend(GetPlayer()->GetGUID().GetCounter()) && GetPlayer()->getLevel() < sWorld->getIntConfig(CONFIG_PARTY_LEVEL_REQ)) + { + SendPartyResult(PARTY_OP_INVITE, membername, ERR_INVITE_RESTRICTED); + return; + } + Group* group = GetPlayer()->GetGroup(); if (group && group->isBGGroup()) group = GetPlayer()->GetOriginalGroup(); @@ -170,6 +183,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) } if (!group->AddInvite(player)) { + group->RemoveAllInvites(); delete group; return; } @@ -488,9 +502,7 @@ void WorldSession::HandleMinimapPingOpcode(WorldPacket& recvData) void WorldSession::HandleRandomRollOpcode(WorldPacket& recvData) { - TC_LOG_DEBUG("network", "WORLD: Received MSG_RANDOM_ROLL"); - - uint32 minimum, maximum, roll; + uint32 minimum, maximum; recvData >> minimum; recvData >> maximum; @@ -499,20 +511,7 @@ void WorldSession::HandleRandomRollOpcode(WorldPacket& recvData) return; /********************/ - // everything's fine, do it - roll = urand(minimum, maximum); - - //TC_LOG_DEBUG("ROLL: MIN: %u, MAX: %u, ROLL: %u", minimum, maximum, roll); - - WorldPacket data(MSG_RANDOM_ROLL, 4+4+4+8); - data << uint32(minimum); - data << uint32(maximum); - data << uint32(roll); - data << uint64(GetPlayer()->GetGUID()); - if (GetPlayer()->GetGroup()) - GetPlayer()->GetGroup()->BroadcastPacket(&data, false); - else - SendPacket(&data); + GetPlayer()->DoRandomRoll(minimum, maximum); } void WorldSession::HandleRaidTargetUpdateOpcode(WorldPacket& recvData) diff --git a/src/server/game/Handlers/GuildHandler.cpp b/src/server/game/Handlers/GuildHandler.cpp index e8f8372d679..3801e974dba 100644 --- a/src/server/game/Handlers/GuildHandler.cpp +++ b/src/server/game/Handlers/GuildHandler.cpp @@ -178,7 +178,7 @@ void WorldSession::HandleGuildSetPublicNoteOpcode(WorldPacket& recvPacket) if (normalizePlayerName(playerName)) if (Guild* guild = GetPlayer()->GetGuild()) - guild->HandleSetMemberNote(this, playerName, note, true); + guild->HandleSetMemberNote(this, playerName, note, false); } void WorldSession::HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket) @@ -192,7 +192,7 @@ void WorldSession::HandleGuildSetOfficerNoteOpcode(WorldPacket& recvPacket) if (normalizePlayerName(playerName)) if (Guild* guild = GetPlayer()->GetGuild()) - guild->HandleSetMemberNote(this, playerName, note, false); + guild->HandleSetMemberNote(this, playerName, note, true); } void WorldSession::HandleGuildRankOpcode(WorldPacket& recvPacket) diff --git a/src/server/game/Handlers/ItemHandler.cpp b/src/server/game/Handlers/ItemHandler.cpp index 7f5d882a912..42ce01708eb 100644 --- a/src/server/game/Handlers/ItemHandler.cpp +++ b/src/server/game/Handlers/ItemHandler.cpp @@ -1095,7 +1095,7 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) return; } - if (!(gift->GetTemplate()->Flags & ITEM_PROTO_FLAG_WRAPPER)) // cheating: non-wrapper wrapper + if (!(gift->GetTemplate()->Flags & ITEM_PROTO_FLAG_IS_WRAPPER)) // cheating: non-wrapper wrapper { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, NULL); return; diff --git a/src/server/game/Handlers/LootHandler.cpp b/src/server/game/Handlers/LootHandler.cpp index 82fdc2e54c7..b0b06b517c8 100644 --- a/src/server/game/Handlers/LootHandler.cpp +++ b/src/server/game/Handlers/LootHandler.cpp @@ -338,7 +338,7 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) else { // Only delete item if no loot or money (unlooted loot is saved to db) or if it isn't an openable item - if (pItem->loot.isLooted() || !(proto->Flags & ITEM_PROTO_FLAG_OPENABLE)) + if (pItem->loot.isLooted() || !(proto->Flags & ITEM_PROTO_FLAG_HAS_LOOT)) player->DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), true); } return; // item can be looted only single player @@ -370,13 +370,10 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) loot->roundRobinPlayer.Clear(); if (Group* group = player->GetGroup()) - { group->SendLooter(creature, NULL); - - // force update of dynamic flags, otherwise other group's players still not able to loot. - creature->ForceValuesUpdateAtIndex(UNIT_DYNAMIC_FLAGS); - } } + // force dynflag update to update looter and lootable info + creature->ForceValuesUpdateAtIndex(UNIT_DYNAMIC_FLAGS); } } diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index aaf6ca39d09..36df5b64f1b 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -35,7 +35,7 @@ bool WorldSession::CanOpenMailBox(ObjectGuid guid) { if (!HasPermission(rbac::RBAC_PERM_COMMAND_MAILBOX)) { - TC_LOG_WARN("cheat", "%s attempt open mailbox in cheating way.", _player->GetName().c_str()); + TC_LOG_WARN("cheat", "%s attempted to open mailbox by using a cheat.", _player->GetName().c_str()); return false; } } @@ -108,7 +108,7 @@ void WorldSession::HandleSendMail(WorldPacket& recvData) if (!receiverGuid) { - TC_LOG_INFO("network", "Player %u is sending mail to %s (GUID: not existed!) with subject %s " + TC_LOG_INFO("network", "Player %u is sending mail to %s (GUID: non-existing!) with subject %s " "and body %s includes %u items, %u copper and %u COD copper with unk1 = %u, unk2 = %u", player->GetGUID().GetCounter(), receiverName.c_str(), subject.c_str(), body.c_str(), items_count, money, COD, stationery, package); @@ -117,7 +117,7 @@ void WorldSession::HandleSendMail(WorldPacket& recvData) } TC_LOG_INFO("network", "Player %u is sending mail to %s (%s) with subject %s and body %s " - "includes %u items, %u copper and %u COD copper with unk1 = %u, unk2 = %u", + "including %u items, %u copper and %u COD copper with unk1 = %u, unk2 = %u", player->GetGUID().GetCounter(), receiverName.c_str(), receiverGuid.ToString().c_str(), subject.c_str(), body.c_str(), items_count, money, COD, stationery, package); diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 5f5a66e7b20..52b36d80202 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -284,7 +284,7 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recvData) continue; uint32 pzoneid = target->GetZoneId(); - uint8 gender = target->GetByteValue(PLAYER_BYTES_3, 0); + uint8 gender = target->GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER); bool z_show = true; for (uint32 i = 0; i < zones_count; ++i) @@ -405,7 +405,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recvData*/) // not set flags if player can't free move to prevent lost state at logout cancel if (GetPlayer()->CanFreeMove()) { - if (GetPlayer()->getStandState() == UNIT_STAND_STATE_STAND) + if (GetPlayer()->GetStandState() == UNIT_STAND_STATE_STAND) GetPlayer()->SetStandState(UNIT_STAND_STATE_SIT); WorldPacket data(SMSG_FORCE_MOVE_ROOT, (8+4)); // guess size @@ -569,7 +569,7 @@ void WorldSession::HandleAddFriendOpcodeCallBack(PreparedQueryResult result, std team = Player::TeamForRace(fields[1].GetUInt8()); friendAccountId = fields[2].GetUInt32(); - if (HasPermission(rbac::RBAC_PERM_ALLOW_GM_FRIEND) || AccountMgr::IsPlayerAccount(AccountMgr::GetSecurity(friendAccountId, realmID))) + if (HasPermission(rbac::RBAC_PERM_ALLOW_GM_FRIEND) || AccountMgr::IsPlayerAccount(AccountMgr::GetSecurity(friendAccountId, realm.Id.Realm))) { if (friendGuid) { @@ -773,17 +773,11 @@ void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recvData) if (status == 0) { - GetPlayer()->clearResurrectRequestData(); // reject + GetPlayer()->ClearResurrectRequestData(); // reject return; } - if (GetPlayer()->IsValidGhoulResurrectRequest(guid)) - { - GetPlayer()->GhoulResurrect(); - return; - } - - if (!GetPlayer()->isResurrectRequestedBy(guid)) + if (!GetPlayer()->IsResurrectRequestedBy(guid)) return; GetPlayer()->ResurrectUsingRequestData(); @@ -890,15 +884,15 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) player->SendTransferAborted(entry->MapID, TRANSFER_ABORT_DIFFICULTY, player->GetDifficulty(entry->IsRaid())); break; case Map::CANNOT_ENTER_NOT_IN_RAID: - if (MapEntry const* entry = sMapStore.LookupEntry(at->target_mapId)) - { - char const* mapName = entry->name[player->GetSession()->GetSessionDbcLocale()]; - TC_LOG_DEBUG("maps", "MAP: Player '%s' must be in a raid group to enter instance '%s'", player->GetName().c_str(), mapName); - // probably there must be special opcode, because client has this string constant in GlobalStrings.lua - player->GetSession()->SendAreaTriggerMessage(player->GetSession()->GetTrinityString(LANG_INSTANCE_RAID_GROUP_ONLY), mapName); - } + { + WorldPacket data(SMSG_RAID_GROUP_ONLY, 4 + 4); + data << uint32(0); + data << uint32(2); // You must be in a raid group to enter this instance. + player->GetSession()->SendPacket(&data); + TC_LOG_DEBUG("maps", "MAP: Player '%s' must be in a raid group to enter instance map %d", player->GetName().c_str(), at->target_mapId); reviveAtTrigger = true; break; + } case Map::CANNOT_ENTER_CORPSE_IN_DIFFERENT_INSTANCE: { WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE); @@ -933,7 +927,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) default: break; } - + if (reviveAtTrigger) // check if the player is touching the areatrigger leading to the map his corpse is on if (!player->IsAlive() && player->HasCorpse()) if (player->GetCorpseLocation().GetMapId() == at->target_mapId) @@ -1062,12 +1056,14 @@ void WorldSession::HandleSetActionButtonOpcode(WorldPacket& recvData) void WorldSession::HandleCompleteCinematic(WorldPacket& /*recvData*/) { - TC_LOG_DEBUG("network", "WORLD: Received CMSG_COMPLETE_CINEMATIC"); + // If player has sight bound to visual waypoint NPC we should remove it + GetPlayer()->GetCinematicMgr()->EndCinematic(); } void WorldSession::HandleNextCinematicCamera(WorldPacket& /*recvData*/) { - TC_LOG_DEBUG("network", "WORLD: Received CMSG_NEXT_CINEMATIC_CAMERA"); + // Sent by client when cinematic actually begun. So we begin the server side process + GetPlayer()->GetCinematicMgr()->BeginCinematic(); } void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recvData) @@ -1163,7 +1159,7 @@ void WorldSession::HandleSetActionBarToggles(WorldPacket& recvData) return; } - GetPlayer()->SetByteValue(PLAYER_FIELD_BYTES, 2, actionBar); + GetPlayer()->SetByteValue(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES, actionBar); } void WorldSession::HandlePlayedTime(WorldPacket& recvData) @@ -1203,7 +1199,7 @@ void WorldSession::HandleInspectOpcode(WorldPacket& recvData) WorldPacket data(SMSG_INSPECT_TALENT, guid_size+4+talent_points); data << player->GetPackGUID(); - if (sWorld->getBoolConfig(CONFIG_TALENTS_INSPECTING) || _player->IsGameMaster()) + if (GetPlayer()->CanBeGameMaster() || sWorld->getIntConfig(CONFIG_TALENTS_INSPECTING) + (GetPlayer()->GetTeamId() == player->GetTeamId()) > 1) player->BuildPlayerTalentsInfoData(&data); else { diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 02702fc5622..64f927a987f 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -473,7 +473,7 @@ void WorldSession::HandleForceSpeedChangeAck(WorldPacket &recvData) { TC_LOG_ERROR("network", "%sSpeedChange player %s is NOT correct (must be %f instead %f), force set to correct value", move_type_name[move_type], _player->GetName().c_str(), _player->GetSpeed(move_type), newspeed); - _player->SetSpeed(move_type, _player->GetSpeedRate(move_type), true); + _player->SetSpeedRate(move_type, _player->GetSpeedRate(move_type)); } else // must be lesser - cheating { diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index 1e00c25a0c3..d02611971cc 100644 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -236,8 +236,8 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) recvData >> guid >> spellId; TC_LOG_DEBUG("network", "WORLD: Received CMSG_TRAINER_BUY_SPELL %s, learn spell id is: %u", guid.ToString().c_str(), spellId); - Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); - if (!unit) + Creature* trainer = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); + if (!trainer) { TC_LOG_DEBUG("network", "WORLD: HandleTrainerBuySpellOpcode - %s not found or you can not interact with him.", guid.ToString().c_str()); return; @@ -247,8 +247,20 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); + // check race for mount trainers + if (trainer->GetCreatureTemplate()->trainer_type == TRAINER_TYPE_MOUNTS) + { + if (uint32 trainerRace = trainer->GetCreatureTemplate()->trainer_race) + if (_player->getRace() != trainerRace) + return; + } + + // check class for class trainers + if (_player->getClass() != trainer->GetCreatureTemplate()->trainer_class && trainer->GetCreatureTemplate()->trainer_type == TRAINER_TYPE_CLASS) + return; + // check present spell in trainer spell list - TrainerSpellData const* trainer_spells = unit->GetTrainerSpells(); + TrainerSpellData const* trainer_spells = trainer->GetTrainerSpells(); if (!trainer_spells) return; @@ -262,7 +274,7 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) return; // apply reputation discount - uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(unit))); + uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(trainer))); // check money requirement if (!_player->HasEnoughMoney(nSpellCost)) @@ -270,8 +282,8 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) _player->ModifyMoney(-int32(nSpellCost)); - unit->SendPlaySpellVisual(179); // 53 SpellCastDirected - unit->SendPlaySpellImpact(_player->GetGUID(), 362); // 113 EmoteSalute + trainer->SendPlaySpellVisual(179); // 53 SpellCastDirected + trainer->SendPlaySpellImpact(_player->GetGUID(), 362); // 113 EmoteSalute // learn explicitly or cast explicitly if (trainer_spell->IsCastable()) diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index 8bfb0070605..17c9c4a58d7 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -595,7 +595,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) Pet* pet = ObjectAccessor::GetPet(*_player, petguid); // check it! - if (!pet || !pet->IsPet() || ((Pet*)pet)->getPetType()!= HUNTER_PET || + if (!pet || !pet->IsPet() || ((Pet*)pet)->getPetType() != HUNTER_PET || !pet->HasByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED) || pet->GetOwnerGUID() != _player->GetGUID() || !pet->GetCharmInfo()) return; diff --git a/src/server/game/Handlers/QueryHandler.cpp b/src/server/game/Handlers/QueryHandler.cpp index ebc9ebde994..1eee9e0d9fe 100644 --- a/src/server/game/Handlers/QueryHandler.cpp +++ b/src/server/game/Handlers/QueryHandler.cpp @@ -133,10 +133,10 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recvData) CreatureQuestItemList const* items = sObjectMgr->GetCreatureQuestItemList(entry); if (items) - for (size_t i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) + for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) data << (i < items->size() ? uint32((*items)[i]) : uint32(0)); else - for (size_t i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) + for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) data << uint32(0); data << uint32(ci->movementId); // CreatureMovementInfo.dbc diff --git a/src/server/game/Handlers/QuestHandler.cpp b/src/server/game/Handlers/QuestHandler.cpp index a7db18deddb..b7aee1778a9 100644 --- a/src/server/game/Handlers/QuestHandler.cpp +++ b/src/server/game/Handlers/QuestHandler.cpp @@ -426,6 +426,7 @@ void WorldSession::HandleQuestLogRemoveQuest(WorldPacket& recvData) } _player->TakeQuestSourceItem(questId, true); // remove quest src item from player + _player->AbandonQuest(questId); // remove all quest items player received before abandoning quest. Note, this does not remove normal drop items that happen to be quest requirements. _player->RemoveActiveQuest(questId); _player->RemoveTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, questId); @@ -640,46 +641,7 @@ void WorldSession::HandleQuestgiverStatusMultipleQuery(WorldPacket& /*recvPacket { TC_LOG_DEBUG("network", "WORLD: Received CMSG_QUESTGIVER_STATUS_MULTIPLE_QUERY"); - uint32 count = 0; - - WorldPacket data(SMSG_QUESTGIVER_STATUS_MULTIPLE, 4); - data << uint32(count); // placeholder - - for (auto itr = _player->m_clientGUIDs.begin(); itr != _player->m_clientGUIDs.end(); ++itr) - { - uint32 questStatus = DIALOG_STATUS_NONE; - - if (itr->IsAnyTypeCreature()) - { - // need also pet quests case support - Creature* questgiver = ObjectAccessor::GetCreatureOrPetOrVehicle(*GetPlayer(), *itr); - if (!questgiver || questgiver->IsHostileTo(_player)) - continue; - if (!questgiver->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER)) - continue; - - questStatus = _player->GetQuestDialogStatus(questgiver); - - data << uint64(questgiver->GetGUID()); - data << uint8(questStatus); - ++count; - } - else if (itr->IsGameObject()) - { - GameObject* questgiver = GetPlayer()->GetMap()->GetGameObject(*itr); - if (!questgiver || questgiver->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER) - continue; - - questStatus = _player->GetQuestDialogStatus(questgiver); - - data << uint64(questgiver->GetGUID()); - data << uint8(questStatus); - ++count; - } - } - - data.put<uint32>(0, count); // write real count - SendPacket(&data); + _player->SendQuestGiverStatusMultiple(); } void WorldSession::HandleQueryQuestsCompleted(WorldPacket & /*recvData*/) diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index 6be1fd30ae3..93e986b0339 100644 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -196,7 +196,7 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) } // Verify that the bag is an actual bag or wrapped item that can be used "normally" - if (!(proto->Flags & ITEM_PROTO_FLAG_OPENABLE) && !item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) + if (!(proto->Flags & ITEM_PROTO_FLAG_HAS_LOOT) && !item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) { pUser->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); TC_LOG_ERROR("network", "Possible hacking attempt: Player %s [guid: %u] tried to open item [guid: %u, entry: %u] which is not openable!", @@ -594,11 +594,11 @@ void WorldSession::HandleMirrorImageDataRequest(WorldPacket& recvData) if (creator->GetTypeId() == TYPEID_PLAYER) { Player* player = creator->ToPlayer(); - data << uint8(player->GetByteValue(PLAYER_BYTES, 0)); // skin - data << uint8(player->GetByteValue(PLAYER_BYTES, 1)); // face - data << uint8(player->GetByteValue(PLAYER_BYTES, 2)); // hair - data << uint8(player->GetByteValue(PLAYER_BYTES, 3)); // haircolor - data << uint8(player->GetByteValue(PLAYER_BYTES_2, 0)); // facialhair + data << uint8(player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_SKIN_ID)); + data << uint8(player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_FACE_ID)); + data << uint8(player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID)); + data << uint8(player->GetByteValue(PLAYER_BYTES, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID)); + data << uint8(player->GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE)); data << uint32(player->GetGuildId()); // unk static EquipmentSlots const itemSlots[] = diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index 3538262ed35..2fbf50cb020 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -38,6 +38,12 @@ InstanceSaveManager::~InstanceSaveManager() { } +InstanceSaveManager* InstanceSaveManager::instance() +{ + static InstanceSaveManager instance; + return &instance; +} + void InstanceSaveManager::Unload() { lock_instLists = true; @@ -447,7 +453,7 @@ time_t InstanceSaveManager::GetSubsequentResetTime(uint32 mapid, Difficulty diff TC_LOG_ERROR("misc", "InstanceSaveManager::GetSubsequentResetTime: not valid difficulty or no reset delay for map %u", mapid); return 0; } - + time_t diff = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR; time_t period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); if (period < DAY) diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index d2b3237b3cf..18e22602e07 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -41,7 +41,7 @@ class Group; - player-instance binds for permanent heroic/raid saves - group-instance binds (both solo and permanent) cache the player binds for the group leader */ -class InstanceSave +class TC_GAME_API InstanceSave { friend class InstanceSaveManager; public: @@ -147,7 +147,7 @@ class InstanceSave typedef std::unordered_map<uint32 /*PAIR32(map, difficulty)*/, time_t /*resetTime*/> ResetTimeByMapDifficultyMap; -class InstanceSaveManager +class TC_GAME_API InstanceSaveManager { friend class InstanceSave; @@ -158,11 +158,7 @@ class InstanceSaveManager public: typedef std::unordered_map<uint32 /*InstanceId*/, InstanceSave*> InstanceSaveHashMap; - static InstanceSaveManager* instance() - { - static InstanceSaveManager instance; - return &instance; - } + static InstanceSaveManager* instance(); void Unload(); diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index 1575b50098f..0887d183a8b 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -29,6 +29,8 @@ #include "Pet.h" #include "WorldSession.h" #include "Opcodes.h" +#include "ScriptReloadMgr.h" +#include "ScriptMgr.h" BossBoundaryData::~BossBoundaryData() { @@ -36,6 +38,18 @@ BossBoundaryData::~BossBoundaryData() delete it->Boundary; } +InstanceScript::InstanceScript(Map* map) : instance(map), completedEncounters(0) +{ +#ifdef TRINITY_API_USE_DYNAMIC_LINKING + uint32 scriptId = sObjectMgr->GetInstanceTemplate(map->GetId())->ScriptId; + auto const scriptname = sObjectMgr->GetScriptName(scriptId); + ASSERT(!scriptname.empty()); + // Acquire a strong reference from the script module + // to keep it loaded until this object is destroyed. + module_reference = sScriptMgr->AcquireModuleReferenceOfScriptName(scriptname); +#endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING +} + void InstanceScript::SaveToDB() { std::string data = GetSaveData(); diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index ce83061e162..3814afe2f4b 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -36,6 +36,7 @@ class Unit; class Player; class GameObject; class Creature; +class ModuleReference; enum EncounterFrameType { @@ -79,7 +80,7 @@ struct BossBoundaryEntry AreaBoundary const* Boundary; }; -struct BossBoundaryData +struct TC_GAME_API BossBoundaryData { typedef std::vector<BossBoundaryEntry> StorageType; typedef StorageType::const_iterator const_iterator; @@ -134,10 +135,10 @@ typedef std::map<uint32 /*entry*/, MinionInfo> MinionInfoMap; typedef std::map<uint32 /*type*/, ObjectGuid /*guid*/> ObjectGuidMap; typedef std::map<uint32 /*entry*/, uint32 /*type*/> ObjectInfoMap; -class InstanceScript : public ZoneScript +class TC_GAME_API InstanceScript : public ZoneScript { public: - explicit InstanceScript(Map* map) : instance(map), completedEncounters(0) { } + explicit InstanceScript(Map* map); virtual ~InstanceScript() { } @@ -289,6 +290,11 @@ class InstanceScript : public ZoneScript ObjectInfoMap _gameObjectInfo; ObjectGuidMap _objectGuids; uint32 completedEncounters; // completed encounter mask, bit indexes are DungeonEncounter.dbc boss numbers, used for packets + + #ifdef TRINITY_API_USE_DYNAMIC_LINKING + // Strong reference to the associated script module + std::shared_ptr<ModuleReference> module_reference; + #endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING }; template<class AI, class T> diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index 19dc210ea5b..260e7ff464f 100644 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -353,7 +353,7 @@ LootItem::LootItem(LootStoreItem const& li) conditions = li.conditions; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); - freeforall = proto && (proto->Flags & ITEM_PROTO_FLAG_PARTY_LOOT); + freeforall = proto && (proto->Flags & ITEM_PROTO_FLAG_MULTI_DROP); follow_loot_rules = proto && (proto->FlagsCu & ITEM_FLAGS_CU_FOLLOW_LOOT_RULES); needs_quest = li.needs_quest; @@ -429,7 +429,7 @@ void Loot::AddItem(LootStoreItem const& item) // non-conditional one-player only items are counted here, // free for all items are counted in FillFFALoot(), // non-ffa conditionals are counted in FillNonQuestNonFFAConditionalLoot() - if (!item.needs_quest && item.conditions.empty() && !(proto->Flags & ITEM_PROTO_FLAG_PARTY_LOOT)) + if (!item.needs_quest && item.conditions.empty() && !(proto->Flags & ITEM_PROTO_FLAG_MULTI_DROP)) ++unlootedCount; } } @@ -704,7 +704,7 @@ void Loot::DeleteLootItemFromContainerItemDB(uint32 itemID) if (_itr->itemid != itemID) continue; - _itr->canSave = true; + _itr->canSave = false; break; } } @@ -786,6 +786,19 @@ uint32 Loot::GetMaxSlotInLootFor(Player* player) const return items.size() + (itr != PlayerQuestItems.end() ? itr->second->size() : 0); } +// return true if there is any item that is lootable for any player (not quest item, FFA or conditional) +bool Loot::hasItemForAll() const +{ + // Gold is always lootable + if (gold) + return true; + + for (LootItem const& item : items) + if (!item.is_looted && !item.freeforall && item.conditions.empty()) + return true; + return false; +} + // return true if there is any FFA, quest or conditional item for the player. bool Loot::hasItemFor(Player* player) const { @@ -1640,7 +1653,7 @@ void LoadLootTemplates_Item() // remove real entries and check existence loot ItemTemplateContainer const* its = sObjectMgr->GetItemTemplateStore(); for (ItemTemplateContainer::const_iterator itr = its->begin(); itr != its->end(); ++itr) - if (lootIdSet.find(itr->second.ItemId) != lootIdSet.end() && itr->second.Flags & ITEM_PROTO_FLAG_OPENABLE) + if (lootIdSet.find(itr->second.ItemId) != lootIdSet.end() && itr->second.Flags & ITEM_PROTO_FLAG_HAS_LOOT) lootIdSet.erase(itr->second.ItemId); // output error for any still listed (not referenced from appropriate table) ids @@ -1871,3 +1884,20 @@ void LoadLootTemplates_Reference() TC_LOG_INFO("server.loading", ">> Loaded refence loot templates in %u ms", GetMSTimeDiffToNow(oldMSTime)); } + +void LoadLootTables() +{ + LoadLootTemplates_Creature(); + LoadLootTemplates_Fishing(); + LoadLootTemplates_Gameobject(); + LoadLootTemplates_Item(); + LoadLootTemplates_Mail(); + LoadLootTemplates_Milling(); + LoadLootTemplates_Pickpocketing(); + LoadLootTemplates_Skinning(); + LoadLootTemplates_Disenchant(); + LoadLootTemplates_Prospecting(); + LoadLootTemplates_Spell(); + + LoadLootTemplates_Reference(); +} diff --git a/src/server/game/Loot/LootMgr.h b/src/server/game/Loot/LootMgr.h index af6f3e56707..a66b8f0b4c5 100644 --- a/src/server/game/Loot/LootMgr.h +++ b/src/server/game/Loot/LootMgr.h @@ -54,7 +54,7 @@ enum RollMask #define MAX_NR_QUEST_ITEMS 32 // unrelated to the number of quest items shown, just for reserve -enum LootMethod +enum LootMethod : uint8 { FREE_FOR_ALL = 0, ROUND_ROBIN = 1, @@ -74,7 +74,7 @@ enum PermissionTypes NONE_PERMISSION = 6 }; -enum LootType +enum LootType : uint8 { LOOT_NONE = 0, @@ -122,7 +122,7 @@ enum LootSlotType class Player; class LootStore; -struct LootStoreItem +struct TC_GAME_API LootStoreItem { uint32 itemid; // id of the item uint32 reference; // referenced TemplateleId @@ -148,7 +148,7 @@ struct LootStoreItem typedef std::set<ObjectGuid::LowType> AllowedLooterSet; -struct LootItem +struct TC_GAME_API LootItem { uint32 itemid; uint32 randomSuffix; @@ -203,7 +203,7 @@ typedef std::unordered_map<uint32, LootTemplate*> LootTemplateMap; typedef std::set<uint32> LootIdSet; -class LootStore +class TC_GAME_API LootStore { public: explicit LootStore(char const* name, char const* entryName, bool ratesAllowed) @@ -239,7 +239,7 @@ class LootStore bool m_ratesAllowed; }; -class LootTemplate +class TC_GAME_API LootTemplate { class LootGroup; // A set of loot definitions for items (refs are not allowed inside) typedef std::vector<LootGroup*> LootGroups; @@ -307,7 +307,7 @@ struct LootView; ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); -struct Loot +struct TC_GAME_API Loot { friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); @@ -382,6 +382,7 @@ struct Loot LootItem* LootItemInSlot(uint32 lootslot, Player* player, QuestItem** qitem = NULL, QuestItem** ffaitem = NULL, QuestItem** conditem = NULL); uint32 GetMaxSlotInLootFor(Player* player) const; + bool hasItemForAll() const; bool hasItemFor(Player* player) const; bool hasOverThresholdItem() const; @@ -409,48 +410,33 @@ struct LootView : loot(_loot), viewer(_viewer), permission(_permission) { } }; -extern LootStore LootTemplates_Creature; -extern LootStore LootTemplates_Fishing; -extern LootStore LootTemplates_Gameobject; -extern LootStore LootTemplates_Item; -extern LootStore LootTemplates_Mail; -extern LootStore LootTemplates_Milling; -extern LootStore LootTemplates_Pickpocketing; -extern LootStore LootTemplates_Reference; -extern LootStore LootTemplates_Skinning; -extern LootStore LootTemplates_Disenchant; -extern LootStore LootTemplates_Prospecting; -extern LootStore LootTemplates_Spell; - -void LoadLootTemplates_Creature(); -void LoadLootTemplates_Fishing(); -void LoadLootTemplates_Gameobject(); -void LoadLootTemplates_Item(); -void LoadLootTemplates_Mail(); -void LoadLootTemplates_Milling(); -void LoadLootTemplates_Pickpocketing(); -void LoadLootTemplates_Skinning(); -void LoadLootTemplates_Disenchant(); -void LoadLootTemplates_Prospecting(); - -void LoadLootTemplates_Spell(); -void LoadLootTemplates_Reference(); - -inline void LoadLootTables() -{ - LoadLootTemplates_Creature(); - LoadLootTemplates_Fishing(); - LoadLootTemplates_Gameobject(); - LoadLootTemplates_Item(); - LoadLootTemplates_Mail(); - LoadLootTemplates_Milling(); - LoadLootTemplates_Pickpocketing(); - LoadLootTemplates_Skinning(); - LoadLootTemplates_Disenchant(); - LoadLootTemplates_Prospecting(); - LoadLootTemplates_Spell(); - - LoadLootTemplates_Reference(); -} +TC_GAME_API extern LootStore LootTemplates_Creature; +TC_GAME_API extern LootStore LootTemplates_Fishing; +TC_GAME_API extern LootStore LootTemplates_Gameobject; +TC_GAME_API extern LootStore LootTemplates_Item; +TC_GAME_API extern LootStore LootTemplates_Mail; +TC_GAME_API extern LootStore LootTemplates_Milling; +TC_GAME_API extern LootStore LootTemplates_Pickpocketing; +TC_GAME_API extern LootStore LootTemplates_Reference; +TC_GAME_API extern LootStore LootTemplates_Skinning; +TC_GAME_API extern LootStore LootTemplates_Disenchant; +TC_GAME_API extern LootStore LootTemplates_Prospecting; +TC_GAME_API extern LootStore LootTemplates_Spell; + +TC_GAME_API void LoadLootTemplates_Creature(); +TC_GAME_API void LoadLootTemplates_Fishing(); +TC_GAME_API void LoadLootTemplates_Gameobject(); +TC_GAME_API void LoadLootTemplates_Item(); +TC_GAME_API void LoadLootTemplates_Mail(); +TC_GAME_API void LoadLootTemplates_Milling(); +TC_GAME_API void LoadLootTemplates_Pickpocketing(); +TC_GAME_API void LoadLootTemplates_Skinning(); +TC_GAME_API void LoadLootTemplates_Disenchant(); +TC_GAME_API void LoadLootTemplates_Prospecting(); + +TC_GAME_API void LoadLootTemplates_Spell(); +TC_GAME_API void LoadLootTemplates_Reference(); + +TC_GAME_API void LoadLootTables(); #endif diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index b0e8a1ebe02..0fc49eba05e 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -49,8 +49,8 @@ MailSender::MailSender(Object* sender, MailStationery stationery) : m_stationery break; default: m_messageType = MAIL_NORMAL; - m_senderId = 0; // will show mail from not existed player - TC_LOG_ERROR("misc", "MailSender::MailSender - Mail have unexpected sender typeid (%u)", sender->GetTypeId()); + m_senderId = 0; // will show mail from non-existing player + TC_LOG_ERROR("misc", "MailSender::MailSender - Mail message contains unexpected sender typeid (%u).", sender->GetTypeId()); break; } } @@ -70,6 +70,13 @@ MailSender::MailSender(Player* sender) m_senderId = sender->GetGUID().GetCounter(); } +MailSender::MailSender(uint32 senderEntry) +{ + m_messageType = MAIL_CREATURE; + m_senderId = senderEntry; + m_stationery = MAIL_STATIONERY_DEFAULT; +} + MailReceiver::MailReceiver(Player* receiver) : m_receiver(receiver), m_receiver_lowguid(receiver->GetGUID().GetCounter()) { } MailReceiver::MailReceiver(Player* receiver, ObjectGuid::LowType receiver_lowguid) : m_receiver(receiver), m_receiver_lowguid(receiver_lowguid) diff --git a/src/server/game/Mails/Mail.h b/src/server/game/Mails/Mail.h index 407edf2badb..ad14e3cecf9 100644 --- a/src/server/game/Mails/Mail.h +++ b/src/server/game/Mails/Mail.h @@ -79,7 +79,7 @@ enum MailShowFlags MAIL_SHOW_RETURN = 0x0010 }; -class MailSender +class TC_GAME_API MailSender { public: // Constructors MailSender(MailMessageType messageType, ObjectGuid::LowType sender_guidlow_or_entry, MailStationery stationery = MAIL_STATIONERY_DEFAULT) @@ -90,6 +90,7 @@ class MailSender MailSender(CalendarEvent* sender); MailSender(AuctionEntry* sender); MailSender(Player* sender); + MailSender(uint32 senderEntry); public: // Accessors MailMessageType GetMailMessageType() const { return m_messageType; } ObjectGuid::LowType GetSenderId() const { return m_senderId; } @@ -100,7 +101,7 @@ class MailSender MailStationery m_stationery; }; -class MailReceiver +class TC_GAME_API MailReceiver { public: // Constructors explicit MailReceiver(ObjectGuid::LowType receiver_lowguid) : m_receiver(NULL), m_receiver_lowguid(receiver_lowguid) { } @@ -114,7 +115,7 @@ class MailReceiver ObjectGuid::LowType m_receiver_lowguid; }; -class MailDraft +class TC_GAME_API MailDraft { typedef std::map<ObjectGuid::LowType, Item*> MailItemMap; @@ -162,7 +163,7 @@ struct MailItemInfo }; typedef std::vector<MailItemInfo> MailItemInfoVec; -struct Mail +struct TC_GAME_API Mail { uint32 messageID; uint8 messageType; diff --git a/src/server/game/Maps/AreaBoundary.h b/src/server/game/Maps/AreaBoundary.h index a134b783ca6..0973d1a6e86 100644 --- a/src/server/game/Maps/AreaBoundary.h +++ b/src/server/game/Maps/AreaBoundary.h @@ -20,7 +20,7 @@ #include "Position.h" -class AreaBoundary +class TC_GAME_API AreaBoundary { public: enum BoundaryType @@ -40,7 +40,7 @@ class AreaBoundary { double d_positionX, d_positionY, d_positionZ; DoublePosition(double x = 0.0, double y = 0.0, double z = 0.0, float o = 0.0f) - : Position(x, y, z, o), d_positionX(x), d_positionY(y), d_positionZ(z) { } + : Position(float(x), float(y), float(z), o), d_positionX(x), d_positionY(y), d_positionZ(z) { } DoublePosition(float x, float y = 0.0f, float z = 0.0f, float o = 0.0f) : Position(x, y, z, o), d_positionX(x), d_positionY(y), d_positionZ(z) { } DoublePosition(const Position& pos) @@ -66,7 +66,7 @@ class AreaBoundary bool m_isInvertedBoundary; }; -class RectangleBoundary : public AreaBoundary +class TC_GAME_API RectangleBoundary : public AreaBoundary { public: // X axis is north/south, Y axis is east/west, larger values are northwest @@ -79,7 +79,7 @@ class RectangleBoundary : public AreaBoundary const float _minX, _maxX, _minY, _maxY; }; -class CircleBoundary : public AreaBoundary +class TC_GAME_API CircleBoundary : public AreaBoundary { public: CircleBoundary(Position const& center, double radius, bool isInverted = false); @@ -95,7 +95,7 @@ class CircleBoundary : public AreaBoundary const double _radiusSq; }; -class EllipseBoundary : public AreaBoundary +class TC_GAME_API EllipseBoundary : public AreaBoundary { public: EllipseBoundary(Position const& center, double radiusX, double radiusY, bool isInverted = false); @@ -109,7 +109,7 @@ class EllipseBoundary : public AreaBoundary const double _radiusYSq, _scaleXSq; }; -class TriangleBoundary : public AreaBoundary +class TC_GAME_API TriangleBoundary : public AreaBoundary { public: TriangleBoundary(Position const& pointA, Position const& pointB, Position const& pointC, bool isInverted = false); @@ -123,7 +123,7 @@ class TriangleBoundary : public AreaBoundary const double _abx, _bcx, _cax, _aby, _bcy, _cay; }; -class ParallelogramBoundary : public AreaBoundary +class TC_GAME_API ParallelogramBoundary : public AreaBoundary { public: // Note: AB must be orthogonal to AD @@ -138,7 +138,7 @@ class ParallelogramBoundary : public AreaBoundary const double _abx, _dax, _aby, _day; }; -class ZRangeBoundary : public AreaBoundary +class TC_GAME_API ZRangeBoundary : public AreaBoundary { public: ZRangeBoundary(float minZ, float maxZ, bool isInverted = false); diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index ca384160ad1..23ca8cbba1a 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -17,6 +17,7 @@ */ #include "Map.h" +#include "MapManager.h" #include "Battleground.h" #include "MMapFactory.h" #include "CellImpl.h" @@ -64,7 +65,7 @@ Map::~Map() } if (!m_scriptSchedule.empty()) - sScriptMgr->DecreaseScheduledScriptCount(m_scriptSchedule.size()); + sMapMgr->DecreaseScheduledScriptCount(m_scriptSchedule.size()); MMAP::MMapFactory::createOrGetMMapManager()->unloadMapInstance(GetId(), i_InstanceId); } @@ -89,7 +90,7 @@ bool Map::ExistMap(uint32 mapid, int gx, int gy) if (fread(&header, sizeof(header), 1, pf) == 1) { if (header.mapMagic.asUInt != MapMagic.asUInt || header.versionMagic.asUInt != MapVersionMagic.asUInt) - TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please recreate using the mapextractor.", + TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please pull your source, recompile tools and recreate maps using the updated mapextractor, then replace your old map files with new files. If you still have problems search on forum for error TCE00018.", fileName, 4, header.mapMagic.asChar, 4, header.versionMagic.asChar, 4, MapMagic.asChar, 4, MapVersionMagic.asChar); else ret = true; @@ -129,9 +130,9 @@ void Map::LoadMMap(int gx, int gy) bool mmapLoadResult = MMAP::MMapFactory::createOrGetMMapManager()->loadMap((sWorld->GetDataPath() + "mmaps").c_str(), GetId(), gx, gy); if (mmapLoadResult) - TC_LOG_DEBUG("maps", "MMAP loaded name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy); + TC_LOG_DEBUG("mmaps", "MMAP loaded name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy); else - TC_LOG_ERROR("maps", "Could not load MMAP name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy); + TC_LOG_ERROR("mmaps", "Could not load MMAP name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy); } void Map::LoadVMap(int gx, int gy) @@ -209,6 +210,13 @@ void Map::LoadMapAndVMap(int gx, int gy) } } +void Map::LoadAllCells() +{ + for (uint32 cellX = 0; cellX < TOTAL_NUMBER_OF_CELLS_PER_MAP; cellX++) + for (uint32 cellY = 0; cellY < TOTAL_NUMBER_OF_CELLS_PER_MAP; cellY++) + LoadGrid((cellX + 0.5f - CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL, (cellY + 0.5f - CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL); +} + void Map::InitStateMachine() { si_GridStates[GRID_STATE_INVALID] = new InvalidState; @@ -594,7 +602,7 @@ bool Map::AddToMap(T* obj) //something, such as vehicle, needs to be update immediately //also, trigger needs to cast spell, if not update, cannot see visual - obj->UpdateObjectVisibility(true); + obj->UpdateObjectVisibilityOnCreate(); return true; } @@ -706,6 +714,15 @@ void Map::Update(const uint32 t_diff) VisitNearbyCellsOf(player, grid_object_update, world_object_update); + // If player is using far sight, visit that object too + if (WorldObject* viewPoint = player->GetViewpoint()) + { + if (Creature* viewCreature = viewPoint->ToCreature()) + VisitNearbyCellsOf(viewCreature, grid_object_update, world_object_update); + else if (DynamicObject* viewObject = viewPoint->ToDynObject()) + VisitNearbyCellsOf(viewObject, grid_object_update, world_object_update); + } + // Handle updates for creatures in combat with player and are more than 60 yards away if (player->IsInCombat()) { @@ -1714,7 +1731,7 @@ bool GridMap::loadData(const char* filename) return true; } - TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please recreate using the mapextractor.", + TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please pull your source, recompile tools and recreate maps using the updated mapextractor, then replace your old map files with new files. If you still have problems search on forum for error TCE00018.", filename, 4, header.mapMagic.asChar, 4, header.versionMagic.asChar, 4, MapMagic.asChar, 4, MapVersionMagic.asChar); fclose(in); return false; @@ -2282,12 +2299,12 @@ inline GridMap* Map::GetGrid(float x, float y) return GridMaps[gx][gy]; } -float Map::GetWaterOrGroundLevel(float x, float y, float z, float* ground /*= NULL*/, bool /*swim = false*/) const +float Map::GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground /*= NULL*/, bool /*swim = false*/) const { if (const_cast<Map*>(this)->GetGrid(x, y)) { // we need ground level (including grid height version) for proper return water level in point - float ground_z = GetHeight(PHASEMASK_NORMAL, x, y, z, true, 50.0f); + float ground_z = GetHeight(phasemask, x, y, z, true, 50.0f); if (ground) *ground = ground_z; @@ -2328,9 +2345,9 @@ float Map::GetHeight(float x, float y, float z, bool checkVMap /*= true*/, float { // we have mapheight and vmapheight and must select more appropriate - // we are already under the surface or vmap height above map heigt + // vmap height above map height // or if the distance of the vmap height is less the land height distance - if (z < mapHeight || vmapHeight > mapHeight || std::fabs(mapHeight - z) > std::fabs(vmapHeight - z)) + if (vmapHeight > mapHeight || std::fabs(mapHeight - z) > std::fabs(vmapHeight - z)) return vmapHeight; else return mapHeight; // better use .map surface height @@ -2428,7 +2445,7 @@ uint32 Map::GetAreaId(float x, float y, float z, bool *isOutdoors) const atEntry = sAreaTableStore.LookupEntry(wmoEntry->areaId); } - uint32 areaId; + uint32 areaId = 0; if (atEntry) areaId = atEntry->ID; @@ -2436,8 +2453,9 @@ uint32 Map::GetAreaId(float x, float y, float z, bool *isOutdoors) const { if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y)) areaId = gmap->getArea(x, y); + // this used while not all *.map files generated (instances) - else + if (!areaId) areaId = i_mapEntry->linked_zone; } @@ -2649,8 +2667,8 @@ void Map::UpdateObjectsVisibilityFor(Player* player, Cell cell, CellCoord cellpa cell.SetNoCreate(); TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier); TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier); - cell.Visit(cellpair, world_notifier, *this, *player, player->GetSightRange()); - cell.Visit(cellpair, grid_notifier, *this, *player, player->GetSightRange()); + cell.Visit(cellpair, world_notifier, *this, *player->m_seer, player->GetSightRange()); + cell.Visit(cellpair, grid_notifier, *this, *player->m_seer, player->GetSightRange()); // send data notifier.SendToSelf(); @@ -2985,15 +3003,15 @@ void Map::RemoveFromActive(DynamicObject* obj) RemoveFromActiveHelper(obj); } -template bool Map::AddToMap(Corpse*); -template bool Map::AddToMap(Creature*); -template bool Map::AddToMap(GameObject*); -template bool Map::AddToMap(DynamicObject*); +template TC_GAME_API bool Map::AddToMap(Corpse*); +template TC_GAME_API bool Map::AddToMap(Creature*); +template TC_GAME_API bool Map::AddToMap(GameObject*); +template TC_GAME_API bool Map::AddToMap(DynamicObject*); -template void Map::RemoveFromMap(Corpse*, bool); -template void Map::RemoveFromMap(Creature*, bool); -template void Map::RemoveFromMap(GameObject*, bool); -template void Map::RemoveFromMap(DynamicObject*, bool); +template TC_GAME_API void Map::RemoveFromMap(Corpse*, bool); +template TC_GAME_API void Map::RemoveFromMap(Creature*, bool); +template TC_GAME_API void Map::RemoveFromMap(GameObject*, bool); +template TC_GAME_API void Map::RemoveFromMap(DynamicObject*, bool); /* ******* Dungeon Instance Maps ******* */ diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index bc2bf72f271..48864180b84 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -154,7 +154,7 @@ struct LiquidData float depth_level; }; -class GridMap +class TC_GAME_API GridMap { uint32 _flags; union{ @@ -253,7 +253,7 @@ typedef std::map<uint32/*leaderDBGUID*/, CreatureGroup*> CreatureGroupHol typedef std::unordered_map<uint32 /*zoneId*/, ZoneDynamicInfo> ZoneDynamicInfoMap; -class Map : public GridRefManager<NGridType> +class TC_GAME_API Map : public GridRefManager<NGridType> { friend class MapReference; public: @@ -277,6 +277,7 @@ class Map : public GridRefManager<NGridType> virtual bool AddPlayerToMap(Player*); virtual void RemovePlayerFromMap(Player*, bool); + template<class T> bool AddToMap(T *); template<class T> void RemoveFromMap(T *, bool); @@ -292,7 +293,8 @@ class Map : public GridRefManager<NGridType> void GameObjectRelocation(GameObject* go, float x, float y, float z, float orientation, bool respawnRelocationOnFail = true); void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float orientation); - template<class T, class CONTAINER> void Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor); + template<class T, class CONTAINER> + void Visit(const Cell& cell, TypeContainerVisitor<T, CONTAINER> &visitor); bool IsRemovalGrid(float x, float y) const { @@ -308,6 +310,7 @@ class Map : public GridRefManager<NGridType> bool GetUnloadLock(const GridCoord &p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); } void SetUnloadLock(const GridCoord &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadExplicitLock(on); } void LoadGrid(float x, float y); + void LoadAllCells(); bool UnloadGrid(NGridType& ngrid, bool pForce); virtual void UnloadAll(); @@ -491,7 +494,7 @@ class Map : public GridRefManager<NGridType> BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast<BattlegroundMap*>(this); else return NULL; } BattlegroundMap const* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast<BattlegroundMap const*>(this); return NULL; } - float GetWaterOrGroundLevel(float x, float y, float z, float* ground = NULL, bool swim = false) const; + float GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground = NULL, bool swim = false) const; float GetHeight(uint32 phasemask, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; bool isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask) const; void Balance() { _dynamicTree.balance(); } @@ -753,7 +756,7 @@ enum InstanceResetMethod INSTANCE_RESET_RESPAWN_DELAY }; -class InstanceMap : public Map +class TC_GAME_API InstanceMap : public Map { public: InstanceMap(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent); @@ -785,7 +788,7 @@ class InstanceMap : public Map uint32 i_script_id; }; -class BattlegroundMap : public Map +class TC_GAME_API BattlegroundMap : public Map { public: BattlegroundMap(uint32 id, time_t, uint32 InstanceId, Map* _parent, uint8 spawnMode); diff --git a/src/server/game/Maps/MapInstanced.cpp b/src/server/game/Maps/MapInstanced.cpp index 47b9b376b1e..58decc05354 100644 --- a/src/server/game/Maps/MapInstanced.cpp +++ b/src/server/game/Maps/MapInstanced.cpp @@ -230,6 +230,9 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, bool load_data = save != NULL; map->CreateInstanceData(load_data); + if (sWorld->getBoolConfig(CONFIG_INSTANCEMAP_LOAD_GRIDS)) + map->LoadAllCells(); + m_InstancedMaps[InstanceId] = map; return map; } diff --git a/src/server/game/Maps/MapInstanced.h b/src/server/game/Maps/MapInstanced.h index 7fa66bde06a..eea54e1f013 100644 --- a/src/server/game/Maps/MapInstanced.h +++ b/src/server/game/Maps/MapInstanced.h @@ -23,7 +23,7 @@ #include "InstanceSaveMgr.h" #include "DBCEnums.h" -class MapInstanced : public Map +class TC_GAME_API MapInstanced : public Map { friend class MapManager; public: diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index e5f364e39f4..79a8b3855e8 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -38,10 +38,10 @@ #include "AchievementMgr.h" MapManager::MapManager() + : _nextInstanceId(0), _scheduledScripts(0) { i_gridCleanUpDelay = sWorld->getIntConfig(CONFIG_INTERVAL_GRIDCLEAN); i_timer.SetInterval(sWorld->getIntConfig(CONFIG_INTERVAL_MAPUPDATE)); - _nextInstanceId = 0; } MapManager::~MapManager() { } @@ -62,6 +62,12 @@ void MapManager::InitializeVisibilityDistanceInfo() (*iter).second->InitVisibilityDistance(); } +MapManager* MapManager::instance() +{ + static MapManager instance; + return &instance; +} + Map* MapManager::CreateBaseMap(uint32 id) { Map* map = FindBaseMap(id); diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index 7f9621593d4..91a26c29150 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -28,14 +28,10 @@ class Transport; struct TransportCreatureProto; -class MapManager +class TC_GAME_API MapManager { public: - static MapManager* instance() - { - static MapManager instance; - return &instance; - } + static MapManager* instance(); Map* CreateBaseMap(uint32 mapId); Map* FindBaseNonInstanceMap(uint32 mapId) const; @@ -130,6 +126,11 @@ class MapManager template<typename Worker> void DoForAllMapsWithMapId(uint32 mapId, Worker&& worker); + void IncreaseScheduledScriptsCount() { ++_scheduledScripts; } + void DecreaseScheduledScriptCount() { --_scheduledScripts; } + void DecreaseScheduledScriptCount(std::size_t count) { _scheduledScripts -= count; } + bool IsScriptScheduled() const { return _scheduledScripts > 0; } + private: typedef std::unordered_map<uint32, Map*> MapMapType; typedef std::vector<bool> InstanceIds; @@ -154,6 +155,9 @@ class MapManager InstanceIds _instanceIds; uint32 _nextInstanceId; MapUpdater m_updater; + + // atomic op counter for active scripts amount + std::atomic<std::size_t> _scheduledScripts; }; template<typename Worker> diff --git a/src/server/game/Scripting/MapScripts.cpp b/src/server/game/Maps/MapScripts.cpp index a01c109b9ca..c5d7bdc64ce 100644 --- a/src/server/game/Scripting/MapScripts.cpp +++ b/src/server/game/Maps/MapScripts.cpp @@ -21,6 +21,7 @@ #include "GridNotifiersImpl.h" #include "GossipDef.h" #include "Map.h" +#include "MapManager.h" #include "ObjectMgr.h" #include "Pet.h" #include "Item.h" @@ -58,7 +59,7 @@ void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, O if (iter->first == 0) immedScript = true; - sScriptMgr->IncreaseScheduledScriptsCount(); + sMapMgr->IncreaseScheduledScriptsCount(); } ///- If one of the effects should be immediate, launch the script execution if (/*start &&*/ immedScript && !i_scriptLock) @@ -86,7 +87,7 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* sou sa.script = &script; m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld->GetGameTime() + delay), sa)); - sScriptMgr->IncreaseScheduledScriptsCount(); + sMapMgr->IncreaseScheduledScriptsCount(); ///- If effects should be immediate, launch the script execution if (delay == 0 && !i_scriptLock) @@ -878,6 +879,6 @@ void Map::ScriptsProcess() m_scriptSchedule.erase(iter); iter = m_scriptSchedule.begin(); - sScriptMgr->DecreaseScheduledScriptCount(); + sMapMgr->DecreaseScheduledScriptCount(); } } diff --git a/src/server/game/Maps/MapUpdater.h b/src/server/game/Maps/MapUpdater.h index 3d0f0b9e7e8..d95011d5a42 100644 --- a/src/server/game/Maps/MapUpdater.h +++ b/src/server/game/Maps/MapUpdater.h @@ -28,7 +28,7 @@ class MapUpdateRequest; class Map; -class MapUpdater +class TC_GAME_API MapUpdater { public: diff --git a/src/server/game/Maps/TransportMgr.cpp b/src/server/game/Maps/TransportMgr.cpp index afbddc5e686..c94dd860dea 100644 --- a/src/server/game/Maps/TransportMgr.cpp +++ b/src/server/game/Maps/TransportMgr.cpp @@ -36,6 +36,12 @@ TransportMgr::TransportMgr() { } TransportMgr::~TransportMgr() { } +TransportMgr* TransportMgr::instance() +{ + static TransportMgr instance; + return &instance; +} + void TransportMgr::Unload() { _transportTemplates.clear(); diff --git a/src/server/game/Maps/TransportMgr.h b/src/server/game/Maps/TransportMgr.h index 0bfb5b7a410..229fea882a4 100644 --- a/src/server/game/Maps/TransportMgr.h +++ b/src/server/game/Maps/TransportMgr.h @@ -82,7 +82,7 @@ struct TransportTemplate typedef std::map<uint32, TransportAnimationEntry const*> TransportPathContainer; typedef std::map<uint32, TransportRotationEntry const*> TransportPathRotationContainer; -struct TransportAnimation +struct TC_GAME_API TransportAnimation { TransportAnimation() : TotalTime(0) { } @@ -96,16 +96,12 @@ struct TransportAnimation typedef std::map<uint32, TransportAnimation> TransportAnimationContainer; -class TransportMgr +class TC_GAME_API TransportMgr { - friend void LoadDBCStores(std::string const&); + friend TC_GAME_API void LoadDBCStores(std::string const&); public: - static TransportMgr* instance() - { - static TransportMgr instance; - return &instance; - } + static TransportMgr* instance(); void Unload(); diff --git a/src/server/game/Miscellaneous/Language.h b/src/server/game/Miscellaneous/Language.h index 62c2a3a1981..143f535ddf5 100644 --- a/src/server/game/Miscellaneous/Language.h +++ b/src/server/game/Miscellaneous/Language.h @@ -112,7 +112,9 @@ enum TrinityStrings LANG_RBAC_PERM_REVOKED_NOT_IN_LIST = 79, LANG_PVPSTATS = 80, LANG_PVPSTATS_DISABLED = 81, - // Free 82 - 95 + LANG_COMMAND_NEARGRAVEYARD = 82, + LANG_COMMAND_NEARGRAVEYARD_NOTFOUND = 83, + // Free 84 - 95 LANG_GUILD_RENAME_ALREADY_EXISTS = 96, @@ -208,7 +210,9 @@ enum TrinityStrings LANG_INVALID_GAMEOBJECT_TYPE = 176, LANG_GAMEOBJECT_DAMAGED = 177, LANG_GRID_POSITION = 178, - // Room for more level 1 179-199 not used + // 179-185 used in 6.x branch + LANG_TRANSPORT_POSITION = 186, + // Room for more level 1 187-199 not used // level 2 chat LANG_NO_SELECTION = 200, @@ -885,7 +889,9 @@ enum TrinityStrings LANG_CHARACTER_DELETED_LIST_LINE_CHAT = 1026, LANG_SQLDRIVER_QUERY_LOGGING_ENABLED = 1027, LANG_SQLDRIVER_QUERY_LOGGING_DISABLED = 1028, - // Room for more level 4 1029-1099 not used + LANG_ACCOUNT_INVALID_BNET_NAME = 1029, // 6.x ONLY + LANG_ACCOUNT_USE_BNET_COMMANDS = 1030, // 6.x enum value name but different text in DB + // Room for more level 4 1031-1099 not used // Level 3 (continue) LANG_ACCOUNT_SETADDON = 1100, @@ -1059,7 +1065,7 @@ enum TrinityStrings LANG_COMMAND_NO_FROZEN_PLAYERS = 5004, LANG_COMMAND_LIST_FREEZE = 5005, LANG_COMMAND_PERMA_FROZEN_PLAYER = 5006, - LANG_INSTANCE_RAID_GROUP_ONLY = 5007, + // = 5007, unused LANG_INSTANCE_CLOSED = 5008, LANG_COMMAND_PLAYED_TO_ALL = 5009, LANG_NPCINFO_LINKGUID = 5010, @@ -1208,6 +1214,8 @@ enum TrinityStrings LANG_CREATURE_NO_INTERIOR_POINT_FOUND = 11011, LANG_CREATURE_MOVEMENT_NOT_BOUNDED = 11012, LANG_CREATURE_MOVEMENT_MAYBE_UNBOUNDED = 11013, - LANG_INSTANCE_BIND_MISMATCH = 11014 + LANG_INSTANCE_BIND_MISMATCH = 11014, + LANG_CREATURE_NOT_AI_ENABLED = 11015, + LANG_SELECT_PLAYER_OR_PET = 11016, }; #endif diff --git a/src/server/game/Miscellaneous/SharedDefines.h b/src/server/game/Miscellaneous/SharedDefines.h index 77d6f739da6..7f77453d00b 100644 --- a/src/server/game/Miscellaneous/SharedDefines.h +++ b/src/server/game/Miscellaneous/SharedDefines.h @@ -23,7 +23,7 @@ #include "DetourNavMesh.h" #include <cassert> -enum SpellEffIndex +enum SpellEffIndex : uint8 { EFFECT_0 = 0, EFFECT_1 = 1, @@ -456,7 +456,7 @@ enum SpellAttr4 enum SpellAttr5 { - SPELL_ATTR5_UNK0 = 0x00000001, // 0 + SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING = 0x00000001, // 0 available casting channel spell when moving SPELL_ATTR5_NO_REAGENT_WHILE_PREP = 0x00000002, // 1 not need reagents if UNIT_FLAG_PREPARATION SPELL_ATTR5_UNK2 = 0x00000004, // 2 SPELL_ATTR5_USABLE_WHILE_STUNNED = 0x00000008, // 3 usable while stunned @@ -828,7 +828,7 @@ enum SpellEffects SPELL_EFFECT_CREATE_ITEM_2 = 157, SPELL_EFFECT_MILLING = 158, SPELL_EFFECT_ALLOW_RENAME_PET = 159, - SPELL_EFFECT_160 = 160, + SPELL_EFFECT_FORCE_CAST_2 = 160, SPELL_EFFECT_TALENT_SPEC_COUNT = 161, SPELL_EFFECT_TALENT_SPEC_SELECT = 162, SPELL_EFFECT_163 = 163, @@ -1490,11 +1490,12 @@ enum GameObjectFlags { GO_FLAG_IN_USE = 0x00000001, // disables interaction while animated GO_FLAG_LOCKED = 0x00000002, // require key, spell, event, etc to be opened. Makes "Locked" appear in tooltip - GO_FLAG_INTERACT_COND = 0x00000004, // cannot interact (condition to interact) + GO_FLAG_INTERACT_COND = 0x00000004, // cannot interact (condition to interact - requires GO_DYNFLAG_LO_ACTIVATE to enable interaction clientside) GO_FLAG_TRANSPORT = 0x00000008, // any kind of transport? Object can transport (elevator, boat, car) GO_FLAG_NOT_SELECTABLE = 0x00000010, // not selectable even in GM mode GO_FLAG_NODESPAWN = 0x00000020, // never despawn, typically for doors, they just change state - GO_FLAG_TRIGGERED = 0x00000040, // typically, summoned objects. Triggered by spell or other events + GO_FLAG_AI_OBSTACLE = 0x00000040, // makes the client register the object in something called AIObstacleMgr, unknown what it does + GO_FLAG_FREEZE_ANIMATION = 0x00000080, GO_FLAG_DAMAGED = 0x00000200, GO_FLAG_DESTROYED = 0x00000400 }; @@ -2531,6 +2532,7 @@ uint32 const CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL = (1 << (CREATURE_TYPE_ME // CreatureFamily.dbc enum CreatureFamily { + CREATURE_FAMILY_NONE = 0, CREATURE_FAMILY_WOLF = 1, CREATURE_FAMILY_CAT = 2, CREATURE_FAMILY_SPIDER = 3, @@ -2576,38 +2578,38 @@ enum CreatureFamily enum CreatureTypeFlags { - CREATURE_TYPEFLAGS_TAMEABLE = 0x00000001, // Tameable by any hunter - CREATURE_TYPEFLAGS_GHOST = 0x00000002, // Creature are also visible for not alive player. Allow gossip interaction if npcflag allow? - CREATURE_TYPEFLAGS_BOSS = 0x00000004, - CREATURE_TYPEFLAGS_UNK3 = 0x00000008, - CREATURE_TYPEFLAGS_UNK4 = 0x00000010, - CREATURE_TYPEFLAGS_UNK5 = 0x00000020, - CREATURE_TYPEFLAGS_UNK6 = 0x00000040, - CREATURE_TYPEFLAGS_DEAD_INTERACT = 0x00000080, // Player can interact with the creature if its dead (not player dead) - CREATURE_TYPEFLAGS_HERBLOOT = 0x00000100, // Can be looted by herbalist - CREATURE_TYPEFLAGS_MININGLOOT = 0x00000200, // Can be looted by miner - CREATURE_TYPEFLAGS_DONT_LOG_DEATH = 0x00000400, // Death event will not show up in combat log - CREATURE_TYPEFLAGS_MOUNTED_COMBAT = 0x00000800, // Creature can remain mounted when entering combat - CREATURE_TYPEFLAGS_AID_PLAYERS = 0x00001000, // ? Can aid any player in combat if in range? - CREATURE_TYPEFLAGS_UNK13 = 0x00002000, - CREATURE_TYPEFLAGS_UNK14 = 0x00004000, // ? Possibly not in use - CREATURE_TYPEFLAGS_ENGINEERLOOT = 0x00008000, // Can be looted by engineer - CREATURE_TYPEFLAGS_EXOTIC = 0x00010000, // Can be tamed by hunter as exotic pet - CREATURE_TYPEFLAGS_UNK17 = 0x00020000, // ? Related to vehicles/pvp? - CREATURE_TYPEFLAGS_UNK18 = 0x00040000, // ? Related to vehicle/siege weapons? - CREATURE_TYPEFLAGS_PROJECTILE_COLLISION = 0x00080000, // Projectiles can collide with this creature - interacts with TARGET_DEST_TRAJ - CREATURE_TYPEFLAGS_UNK20 = 0x00100000, - CREATURE_TYPEFLAGS_UNK21 = 0x00200000, - CREATURE_TYPEFLAGS_UNK22 = 0x00400000, - CREATURE_TYPEFLAGS_UNK23 = 0x00800000, // ? First seen in 3.2.2. Related to banner/backpack of creature/companion? - CREATURE_TYPEFLAGS_UNK24 = 0x01000000, - CREATURE_TYPEFLAGS_UNK25 = 0x02000000, - CREATURE_TYPEFLAGS_PARTY_MEMBER = 0x04000000, //! Creature can be targeted by spells that require target to be in caster's party/raid - CREATURE_TYPEFLAGS_UNK27 = 0x08000000, - CREATURE_TYPEFLAGS_UNK28 = 0x10000000, - CREATURE_TYPEFLAGS_UNK29 = 0x20000000, - CREATURE_TYPEFLAGS_UNK30 = 0x40000000, - CREATURE_TYPEFLAGS_UNK31 = 0x80000000 + CREATURE_TYPE_FLAG_TAMEABLE_PET = 0x00000001, // Makes the mob tameable (must also be a beast and have family set) + CREATURE_TYPE_FLAG_GHOST_VISIBLE = 0x00000002, // Creature are also visible for not alive player. Allow gossip interaction if npcflag allow? + CREATURE_TYPE_FLAG_BOSS_MOB = 0x00000004, // Changes creature's visible level to "??" in the creature's portrait - Immune Knockback. + CREATURE_TYPE_FLAG_DO_NOT_PLAY_WOUND_PARRY_ANIMATION = 0x00000008, + CREATURE_TYPE_FLAG_HIDE_FACTION_TOOLTIP = 0x00000010, + CREATURE_TYPE_FLAG_UNK5 = 0x00000020, // Sound related + CREATURE_TYPE_FLAG_SPELL_ATTACKABLE = 0x00000040, + CREATURE_TYPE_FLAG_CAN_INTERACT_WHILE_DEAD = 0x00000080, // Player can interact with the creature if its dead (not player dead) + CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL = 0x00000100, // Can be looted by herbalist + CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL = 0x00000200, // Can be looted by miner + CREATURE_TYPE_FLAG_DO_NOT_LOG_DEATH = 0x00000400, // Death event will not show up in combat log + CREATURE_TYPE_FLAG_MOUNTED_COMBAT_ALLOWED = 0x00000800, // Creature can remain mounted when entering combat + CREATURE_TYPE_FLAG_CAN_ASSIST = 0x00001000, // ? Can aid any player in combat if in range? + CREATURE_TYPE_FLAG_IS_PET_BAR_USED = 0x00002000, + CREATURE_TYPE_FLAG_MASK_UID = 0x00004000, + CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL = 0x00008000, // Can be looted by engineer + CREATURE_TYPE_FLAG_EXOTIC_PET = 0x00010000, // Can be tamed by hunter as exotic pet + CREATURE_TYPE_FLAG_USE_DEFAULT_COLLISION_BOX = 0x00020000, // Collision related. (always using default collision box?) + CREATURE_TYPE_FLAG_IS_SIEGE_WEAPON = 0x00040000, + CREATURE_TYPE_FLAG_CAN_COLLIDE_WITH_MISSILES = 0x00080000, // Projectiles can collide with this creature - interacts with TARGET_DEST_TRAJ + CREATURE_TYPE_FLAG_HIDE_NAME_PLATE = 0x00100000, + CREATURE_TYPE_FLAG_DO_NOT_PLAY_MOUNTED_ANIMATIONS = 0x00200000, + CREATURE_TYPE_FLAG_IS_LINK_ALL = 0x00400000, + CREATURE_TYPE_FLAG_INTERACT_ONLY_WITH_CREATOR = 0x00800000, + CREATURE_TYPE_FLAG_DO_NOT_PLAY_UNIT_EVENT_SOUNDS = 0x01000000, + CREATURE_TYPE_FLAG_HAS_NO_SHADOW_BLOB = 0x02000000, + CREATURE_TYPE_FLAG_TREAT_AS_RAID_UNIT = 0x04000000, // ! Creature can be targeted by spells that require target to be in caster's party/raid + CREATURE_TYPE_FLAG_FORCE_GOSSIP = 0x08000000, // Allows the creature to display a single gossip option. + CREATURE_TYPE_FLAG_DO_NOT_SHEATHE = 0x10000000, + CREATURE_TYPE_FLAG_DO_NOT_TARGET_ON_INTERACTION = 0x20000000, + CREATURE_TYPE_FLAG_DO_NOT_RENDER_OBJECT_NAME = 0x40000000, + CREATURE_TYPE_FLAG_UNIT_IS_QUEST_BOSS = 0x80000000 // Not verified }; enum CreatureEliteType diff --git a/src/server/game/Movement/MotionMaster.cpp b/src/server/game/Movement/MotionMaster.cpp index 05948b987ad..26873451649 100644 --- a/src/server/game/Movement/MotionMaster.cpp +++ b/src/server/game/Movement/MotionMaster.cpp @@ -193,7 +193,7 @@ void MotionMaster::MoveRandom(float spawndist) { if (_owner->GetTypeId() == TYPEID_UNIT) { - TC_LOG_DEBUG("misc", "Creature (GUID: %u) start moving random", _owner->GetGUID().GetCounter()); + TC_LOG_DEBUG("misc", "Creature (GUID: %u) started random movement.", _owner->GetGUID().GetCounter()); Mutate(new RandomMovementGenerator<Creature>(spawndist), MOTION_SLOT_IDLE); } } @@ -204,22 +204,22 @@ void MotionMaster::MoveTargetedHome() if (_owner->GetTypeId() == TYPEID_UNIT && !_owner->ToCreature()->GetCharmerOrOwnerGUID()) { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted home", _owner->GetEntry(), _owner->GetGUID().GetCounter()); + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted home.", _owner->GetEntry(), _owner->GetGUID().GetCounter()); Mutate(new HomeMovementGenerator<Creature>(), MOTION_SLOT_ACTIVE); } else if (_owner->GetTypeId() == TYPEID_UNIT && _owner->ToCreature()->GetCharmerOrOwnerGUID()) { - TC_LOG_DEBUG("misc", "Pet or controlled creature (Entry: %u GUID: %u) targeting home", _owner->GetEntry(), _owner->GetGUID().GetCounter()); + TC_LOG_DEBUG("misc", "Pet or controlled creature (Entry: %u GUID: %u) is targeting home.", _owner->GetEntry(), _owner->GetGUID().GetCounter()); Unit* target = _owner->ToCreature()->GetCharmerOrOwner(); if (target) { - TC_LOG_DEBUG("misc", "Following %s (GUID: %u)", target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : ((Creature*)target)->GetSpawnId()); + TC_LOG_DEBUG("misc", "Following %s (GUID: %u).", target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : ((Creature*)target)->GetSpawnId()); Mutate(new FollowMovementGenerator<Creature>(target, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE), MOTION_SLOT_ACTIVE); } } else { - TC_LOG_ERROR("misc", "Player (GUID: %u) attempt targeted home", _owner->GetGUID().GetCounter()); + TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to move towards target home.", _owner->GetGUID().GetCounter()); } } @@ -241,7 +241,7 @@ void MotionMaster::MoveConfused() void MotionMaster::MoveChase(Unit* target, float dist, float angle) { // ignore movement request if target not exist - if (!target || target == _owner || _owner->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) + if (!target || target == _owner) return; //_owner->ClearUnitState(UNIT_STATE_FOLLOW); @@ -266,20 +266,20 @@ void MotionMaster::MoveChase(Unit* target, float dist, float angle) void MotionMaster::MoveFollow(Unit* target, float dist, float angle, MovementSlot slot) { // ignore movement request if target not exist - if (!target || target == _owner || _owner->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) + if (!target || target == _owner) return; //_owner->AddUnitState(UNIT_STATE_FOLLOW); if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_DEBUG("misc", "Player (GUID: %u) follow to %s (GUID: %u)", _owner->GetGUID().GetCounter(), + TC_LOG_DEBUG("misc", "Player (GUID: %u) follows %s (GUID: %u).", _owner->GetGUID().GetCounter(), target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId()); Mutate(new FollowMovementGenerator<Player>(target, dist, angle), slot); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) follow to %s (GUID: %u)", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) follows %s (GUID: %u).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), target->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", target->GetTypeId() == TYPEID_PLAYER ? target->GetGUID().GetCounter() : target->ToCreature()->GetSpawnId()); @@ -291,23 +291,44 @@ void MotionMaster::MovePoint(uint32 id, float x, float y, float z, bool generate { if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_DEBUG("misc", "Player (GUID: %u) targeted point (Id: %u X: %f Y: %f Z: %f)", _owner->GetGUID().GetCounter(), id, x, y, z); + TC_LOG_DEBUG("misc", "Player (GUID: %u) targeted point (Id: %u X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), id, x, y, z); Mutate(new PointMovementGenerator<Player>(id, x, y, z, generatePath), MOTION_SLOT_ACTIVE); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted point (ID: %u X: %f Y: %f Z: %f)", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) targeted point (ID: %u X: %f Y: %f Z: %f).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), id, x, y, z); Mutate(new PointMovementGenerator<Creature>(id, x, y, z, generatePath), MOTION_SLOT_ACTIVE); } } +void MotionMaster::MoveCloserAndStop(uint32 id, Unit* target, float distance) +{ + float distanceToTravel = _owner->GetExactDist2d(target) - distance; + if (distanceToTravel > 0.0f) + { + float angle = _owner->GetAngle(target); + float destx = _owner->GetPositionX() + distanceToTravel * std::cos(angle); + float desty = _owner->GetPositionY() + distanceToTravel * std::sin(angle); + MovePoint(id, destx, desty, target->GetPositionZ()); + } + else + { + // we are already close enough. We just need to turn toward the target without changing position. + Movement::MoveSplineInit init(_owner); + init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZMinusOffset()); + init.SetFacing(target); + init.Launch(); + Mutate(new EffectMovementGenerator(id), MOTION_SLOT_ACTIVE); + } +} + void MotionMaster::MoveLand(uint32 id, Position const& pos) { float x, y, z; pos.GetPosition(x, y, z); - TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f)", _owner->GetEntry(), id, x, y, z); + TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f).", _owner->GetEntry(), id, x, y, z); Movement::MoveSplineInit init(_owner); init.MoveTo(x, y, z); @@ -321,7 +342,7 @@ void MotionMaster::MoveTakeoff(uint32 id, Position const& pos) float x, y, z; pos.GetPosition(x, y, z); - TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f)", _owner->GetEntry(), id, x, y, z); + TC_LOG_DEBUG("misc", "Creature (Entry: %u) landing point (ID: %u X: %f Y: %f Z: %f).", _owner->GetEntry(), id, x, y, z); Movement::MoveSplineInit init(_owner); init.MoveTo(x, y, z); @@ -371,7 +392,7 @@ void MotionMaster::MoveJumpTo(float angle, float speedXY, float speedZ) void MotionMaster::MoveJump(float x, float y, float z, float o, float speedXY, float speedZ, uint32 id, bool hasOrientation /* = false*/) { - TC_LOG_DEBUG("misc", "Unit (GUID: %u) jump to point (X: %f Y: %f Z: %f)", _owner->GetGUID().GetCounter(), x, y, z); + TC_LOG_DEBUG("misc", "Unit (GUID: %u) jumps to point (X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), x, y, z); if (speedXY <= 0.1f) return; @@ -449,7 +470,7 @@ void MotionMaster::MoveFall(uint32 id /*=0*/) float tz = _owner->GetMap()->GetHeight(_owner->GetPhaseMask(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ(), true, MAX_FALL_DISTANCE); if (tz <= INVALID_HEIGHT) { - TC_LOG_DEBUG("misc", "MotionMaster::MoveFall: unable retrive a proper height at map %u (x: %f, y: %f, z: %f).", + TC_LOG_DEBUG("misc", "MotionMaster::MoveFall: unable to retrieve a proper height at map %u (x: %f, y: %f, z: %f).", _owner->GetMap()->GetId(), _owner->GetPositionX(), _owner->GetPositionY(), _owner->GetPositionZ()); return; } @@ -458,11 +479,12 @@ void MotionMaster::MoveFall(uint32 id /*=0*/) if (std::fabs(_owner->GetPositionZ() - tz) < 0.1f) return; + _owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING); + _owner->m_movementInfo.SetFallTime(0); + + // don't run spline movement for players if (_owner->GetTypeId() == TYPEID_PLAYER) - { - _owner->AddUnitMovementFlag(MOVEMENTFLAG_FALLING); - _owner->m_movementInfo.SetFallTime(0); - } + return; Movement::MoveSplineInit init(_owner); init.MoveTo(_owner->GetPositionX(), _owner->GetPositionY(), tz, false); @@ -478,12 +500,12 @@ void MotionMaster::MoveCharge(float x, float y, float z, float speed /*= SPEED_C if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_DEBUG("misc", "Player (GUID: %u) charge point (X: %f Y: %f Z: %f)", _owner->GetGUID().GetCounter(), x, y, z); + TC_LOG_DEBUG("misc", "Player (GUID: %u) charged point (X: %f Y: %f Z: %f).", _owner->GetGUID().GetCounter(), x, y, z); Mutate(new PointMovementGenerator<Player>(id, x, y, z, generatePath, speed), MOTION_SLOT_CONTROLLED); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) charge point (X: %f Y: %f Z: %f)", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) charged point (X: %f Y: %f Z: %f).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), x, y, z); Mutate(new PointMovementGenerator<Creature>(id, x, y, z, generatePath, speed), MOTION_SLOT_CONTROLLED); } @@ -506,13 +528,14 @@ void MotionMaster::MoveSeekAssistance(float x, float y, float z) { if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_ERROR("misc", "Player (GUID: %u) attempt to seek assistance", _owner->GetGUID().GetCounter()); + TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to seek assistance.", _owner->GetGUID().GetCounter()); } else { TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) seek assistance (X: %f Y: %f Z: %f)", _owner->GetEntry(), _owner->GetGUID().GetCounter(), x, y, z); _owner->AttackStop(); + _owner->CastStop(); _owner->ToCreature()->SetReactState(REACT_PASSIVE); Mutate(new AssistanceMovementGenerator(x, y, z), MOTION_SLOT_ACTIVE); } @@ -522,11 +545,11 @@ void MotionMaster::MoveSeekAssistanceDistract(uint32 time) { if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_ERROR("misc", "Player (GUID: %u) attempt to call distract after assistance", _owner->GetGUID().GetCounter()); + TC_LOG_ERROR("misc", "Player (GUID: %u) attempted to call distract assistance.", _owner->GetGUID().GetCounter()); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) is distracted after assistance call (Time: %u)", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) is distracted after assistance call (Time: %u).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), time); Mutate(new AssistanceDistractMovementGenerator(time), MOTION_SLOT_ACTIVE); } @@ -539,14 +562,14 @@ void MotionMaster::MoveFleeing(Unit* enemy, uint32 time) if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_DEBUG("misc", "Player (GUID: %u) flee from %s (GUID: %u)", _owner->GetGUID().GetCounter(), + TC_LOG_DEBUG("misc", "Player (GUID: %u) flees from %s (GUID: %u).", _owner->GetGUID().GetCounter(), enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUID().GetCounter() : enemy->ToCreature()->GetSpawnId()); Mutate(new FleeingMovementGenerator<Player>(enemy->GetGUID()), MOTION_SLOT_CONTROLLED); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) flee from %s (GUID: %u)%s", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) flees from %s (GUID: %u)%s.", _owner->GetEntry(), _owner->GetGUID().GetCounter(), enemy->GetTypeId() == TYPEID_PLAYER ? "player" : "creature", enemy->GetTypeId() == TYPEID_PLAYER ? enemy->GetGUID().GetCounter() : enemy->ToCreature()->GetSpawnId(), @@ -564,20 +587,20 @@ void MotionMaster::MoveTaxiFlight(uint32 path, uint32 pathnode) { if (path < sTaxiPathNodesByPath.size()) { - TC_LOG_DEBUG("misc", "%s taxi to (Path %u node %u)", _owner->GetName().c_str(), path, pathnode); + TC_LOG_DEBUG("misc", "%s taxi to (Path %u node %u).", _owner->GetName().c_str(), path, pathnode); FlightPathMovementGenerator* mgen = new FlightPathMovementGenerator(pathnode); mgen->LoadPath(_owner->ToPlayer()); Mutate(mgen, MOTION_SLOT_CONTROLLED); } else { - TC_LOG_ERROR("misc", "%s attempt taxi to (not existed Path %u node %u)", + TC_LOG_ERROR("misc", "%s attempted taxi to (non-existing Path %u node %u).", _owner->GetName().c_str(), path, pathnode); } } else { - TC_LOG_ERROR("misc", "Creature (Entry: %u GUID: %u) attempt taxi to (Path %u node %u)", + TC_LOG_ERROR("misc", "Creature (Entry: %u GUID: %u) attempted taxi to (Path %u node %u).", _owner->GetEntry(), _owner->GetGUID().GetCounter(), path, pathnode); } } @@ -589,11 +612,11 @@ void MotionMaster::MoveDistract(uint32 timer) if (_owner->GetTypeId() == TYPEID_PLAYER) { - TC_LOG_DEBUG("misc", "Player (GUID: %u) distracted (timer: %u)", _owner->GetGUID().GetCounter(), timer); + TC_LOG_DEBUG("misc", "Player (GUID: %u) distracted (timer: %u).", _owner->GetGUID().GetCounter(), timer); } else { - TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) (timer: %u)", + TC_LOG_DEBUG("misc", "Creature (Entry: %u GUID: %u) distracted (timer: %u)", _owner->GetEntry(), _owner->GetGUID().GetCounter(), timer); } @@ -645,7 +668,7 @@ void MotionMaster::MovePath(uint32 path_id, bool repeatable) //Mutate(new WaypointMovementGenerator<Player>(path_id, repeatable)): Mutate(new WaypointMovementGenerator<Creature>(path_id, repeatable), MOTION_SLOT_IDLE); - TC_LOG_DEBUG("misc", "%s (GUID: %u) start moving over path(Id:%u, repeatable: %s)", + TC_LOG_DEBUG("misc", "%s (GUID: %u) starts moving over path(Id:%u, repeatable: %s).", _owner->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature", _owner->GetGUID().GetCounter(), path_id, repeatable ? "YES" : "NO"); } diff --git a/src/server/game/Movement/MotionMaster.h b/src/server/game/Movement/MotionMaster.h index 76ae12986d5..005f10b44af 100644 --- a/src/server/game/Movement/MotionMaster.h +++ b/src/server/game/Movement/MotionMaster.h @@ -79,7 +79,7 @@ enum RotateDirection // assume it is 25 yard per 0.6 second #define SPEED_CHARGE 42.0f -class MotionMaster //: private std::stack<MovementGenerator *> +class TC_GAME_API MotionMaster //: private std::stack<MovementGenerator *> { private: //typedef std::stack<MovementGenerator *> Impl; @@ -173,6 +173,12 @@ class MotionMaster //: private std::stack<MovementGenerator *> { MovePoint(id, pos.m_positionX, pos.m_positionY, pos.m_positionZ, generatePath); } void MovePoint(uint32 id, float x, float y, float z, bool generatePath = true); + /* Makes the unit move toward the target until it is at a certain distance from it. The unit then stops. + Only works in 2D. + This method doesn't account for any movement done by the target. in other words, it only works if the target is stationary. + */ + void MoveCloserAndStop(uint32 id, Unit* target, float distance); + // These two movement types should only be used with creatures having landing/takeoff animations void MoveLand(uint32 id, Position const& pos); void MoveTakeoff(uint32 id, Position const& pos); diff --git a/src/server/game/Movement/MovementGenerator.h b/src/server/game/Movement/MovementGenerator.h index 56e5dc7058a..d9dd17fabc2 100755 --- a/src/server/game/Movement/MovementGenerator.h +++ b/src/server/game/Movement/MovementGenerator.h @@ -27,7 +27,7 @@ class Unit; -class MovementGenerator +class TC_GAME_API MovementGenerator { public: virtual ~MovementGenerator(); diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp index 108276c951a..6f6a8037d47 100755 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp @@ -23,11 +23,6 @@ #include "MoveSpline.h" #include "Player.h" -#ifdef MAP_BASED_RAND_GEN -#define rand_norm() unit.rand_norm() -#define urand(a, b) unit.urand(a, b) -#endif - template<class T> void ConfusedMovementGenerator<T>::DoInitialize(T* unit) { diff --git a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp index 6cdd29986bb..4cf896c6d98 100644 --- a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp @@ -38,6 +38,12 @@ void FleeingMovementGenerator<T>::_setTargetLocation(T* owner) if (owner->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED)) return; + if (owner->HasUnitState(UNIT_STATE_CASTING) && !owner->CanMoveDuringChannel()) + { + owner->CastStop(); + return; + } + owner->AddUnitState(UNIT_STATE_FLEEING_MOVE); float x, y, z; diff --git a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h index 9aa778c5651..161f9e3e970 100755 --- a/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/IdleMovementGenerator.h @@ -32,7 +32,7 @@ class IdleMovementGenerator : public MovementGenerator MovementGeneratorType GetMovementGeneratorType() const override { return IDLE_MOTION_TYPE; } }; -extern IdleMovementGenerator si_idleMovement; +TC_GAME_API extern IdleMovementGenerator si_idleMovement; class RotateMovementGenerator : public MovementGenerator { diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp index 2e013c44ae8..feea0ce734d 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp @@ -26,13 +26,15 @@ #define RUNNING_CHANCE_RANDOMMV 20 //will be "1 / RUNNING_CHANCE_RANDOMMV" -#ifdef MAP_BASED_RAND_GEN -#define rand_norm() creature.rand_norm() -#endif - template<> void RandomMovementGenerator<Creature>::_setRandomLocation(Creature* creature) { + if (creature->HasUnitState(UNIT_STATE_CASTING) && !creature->CanMoveDuringChannel()) + { + creature->CastStop(); + return; + } + float respX, respY, respZ, respO, destX, destY, destZ, travelDistZ; creature->GetHomePosition(respX, respY, respZ, respO); Map const* map = creature->GetBaseMap(); @@ -61,7 +63,7 @@ void RandomMovementGenerator<Creature>::_setRandomLocation(Creature* creature) // Limit height change const float distanceZ = float(rand_norm()) * travelDistZ/2.0f; destZ = respZ + distanceZ; - float levelZ = map->GetWaterOrGroundLevel(destX, destY, destZ-2.0f); + float levelZ = map->GetWaterOrGroundLevel(creature->GetPhaseMask(), destX, destY, destZ-2.5f); // Problem here, we must fly above the ground and water, not under. Let's try on next tick if (levelZ >= destZ) @@ -145,6 +147,9 @@ void RandomMovementGenerator<Creature>::DoFinalize(Creature* creature) template<> bool RandomMovementGenerator<Creature>::DoUpdate(Creature* creature, const uint32 diff) { + if (!creature || !creature->IsAlive()) + return false; + if (creature->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_DISTRACTED)) { i_nextMoveTime.Reset(0); // Expire the timer diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp index b595059557a..2a95952d793 100644 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp @@ -36,8 +36,14 @@ void TargetedMovementGeneratorMedium<T, D>::_setTargetLocation(T* owner, bool up if (owner->HasUnitState(UNIT_STATE_NOT_MOVE)) return; + if (owner->HasUnitState(UNIT_STATE_CASTING) && !owner->CanMoveDuringChannel()) + return; + if (owner->GetTypeId() == TYPEID_UNIT && !i_target->isInAccessiblePlaceFor(owner->ToCreature())) + { + owner->ToCreature()->SetCannotReachTarget(true); return; + } if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsFocusing(nullptr, true)) return; @@ -48,6 +54,9 @@ void TargetedMovementGeneratorMedium<T, D>::_setTargetLocation(T* owner, bool up { if (!i_offset) { + if (i_target->IsWithinDistInMap(owner, CONTACT_DISTANCE)) + return; + // to nearest contact position i_target->GetContactPoint(owner, x, y, z); } @@ -64,8 +73,8 @@ void TargetedMovementGeneratorMedium<T, D>::_setTargetLocation(T* owner, bool up // doing a "dance" while fighting if (owner->IsPet() && i_target->GetTypeId() == TYPEID_PLAYER) { - dist = i_target->GetCombatReach(); - size = i_target->GetCombatReach() - i_target->GetObjectSize(); + dist = 1.0f; //i_target->GetCombatReach(); + size = 1.0f; //i_target->GetCombatReach() - i_target->GetObjectSize(); } else { @@ -99,8 +108,10 @@ void TargetedMovementGeneratorMedium<T, D>::_setTargetLocation(T* owner, bool up bool result = i_path->CalculatePath(x, y, z, forceDest); if (!result || (i_path->GetPathType() & PATHFIND_NOPATH)) { - // Cant reach target + // can't reach target i_recalculateTravel = true; + if (owner->GetTypeId() == TYPEID_UNIT) + owner->ToCreature()->SetCannotReachTarget(true); return; } @@ -108,6 +119,8 @@ void TargetedMovementGeneratorMedium<T, D>::_setTargetLocation(T* owner, bool up i_targetReached = false; i_recalculateTravel = false; owner->AddUnitState(UNIT_STATE_CHASE); + if (owner->GetTypeId() == TYPEID_UNIT) + owner->ToCreature()->SetCannotReachTarget(false); Movement::MoveSplineInit init(owner); init.MovebyPath(i_path->GetPath()); @@ -136,7 +149,7 @@ bool TargetedMovementGeneratorMedium<T, D>::DoUpdate(T* owner, uint32 time_diff) } // prevent movement while casting spells with cast time or channel time - if (owner->HasUnitState(UNIT_STATE_CASTING)) + if (owner->HasUnitState(UNIT_STATE_CASTING) && !owner->CanMoveDuringChannel()) { if (!owner->IsStopped()) owner->StopMoving(); @@ -155,8 +168,15 @@ bool TargetedMovementGeneratorMedium<T, D>::DoUpdate(T* owner, uint32 time_diff) if (i_recheckDistance.Passed()) { i_recheckDistance.Reset(100); + //More distance let have better performance, less distance let have more sensitive reaction at target move. - float allowed_dist = owner->GetCombatReach() + sWorld->getRate(RATE_TARGET_POS_RECALCULATION_RANGE); + float allowed_dist = 0.0f; + + if (owner->IsPet() && (owner->GetCharmerOrOwnerGUID() == i_target->GetGUID())) + allowed_dist = 1.0f; // pet following owner + else + allowed_dist = owner->GetCombatReach() + sWorld->getRate(RATE_TARGET_POS_RECALCULATION_RANGE); + G3D::Vector3 dest = owner->movespline->FinalDestination(); if (owner->movespline->onTransport) if (TransportBase* transport = owner->GetDirectTransport()) @@ -198,6 +218,8 @@ void ChaseMovementGenerator<T>::_reachTarget(T* owner) { if (owner->IsWithinMeleeRange(this->i_target.getTarget())) owner->Attack(this->i_target.getTarget(), true); + if (owner->GetTypeId() == TYPEID_UNIT) + owner->ToCreature()->SetCannotReachTarget(false); } template<> @@ -265,9 +287,9 @@ void FollowMovementGenerator<Creature>::_updateSpeed(Creature* owner) if (!owner->IsPet() || !owner->IsInWorld() || !i_target.isValid() || i_target->GetGUID() != owner->GetOwnerGUID()) return; - owner->UpdateSpeed(MOVE_RUN, true); - owner->UpdateSpeed(MOVE_WALK, true); - owner->UpdateSpeed(MOVE_SWIM, true); + owner->UpdateSpeed(MOVE_RUN); + owner->UpdateSpeed(MOVE_WALK); + owner->UpdateSpeed(MOVE_SWIM); } template<> diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h index 7103eaace55..9250b666484 100755 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.h @@ -50,7 +50,7 @@ class TargetedMovementGeneratorMedium : public MovementGeneratorMedium< T, D >, bool DoUpdate(T*, uint32); Unit* GetTarget() const { return i_target.getTarget(); } - void unitSpeedChanged() { i_recalculateTravel = true; } + void unitSpeedChanged() override { i_recalculateTravel = true; } bool IsReachable() const { return (i_path) ? (i_path->GetPathType() & PATHFIND_NORMAL) : true; } protected: void _setTargetLocation(T* owner, bool updateDestination); diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index 48d29b3259b..2ffa1a644eb 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -213,7 +213,7 @@ bool WaypointMovementGenerator<Creature>::DoUpdate(Creature* creature, uint32 di creature->SetHomePosition(creature->GetPosition()); if (creature->IsStopped()) - Stop(STOP_TIME_FOR_PLAYER); + Stop(sWorld->getIntConfig(CONFIG_CREATURE_STOP_FOR_PLAYER)); else if (creature->movespline->Finalized()) { OnArrived(creature); @@ -315,7 +315,7 @@ void FlightPathMovementGenerator::DoFinalize(Player* player) player->ClearUnitState(UNIT_STATE_IN_FLIGHT); player->Dismount(); - player->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); + player->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_TAXI_FLIGHT); if (player->m_taxi.empty()) { @@ -335,7 +335,7 @@ void FlightPathMovementGenerator::DoReset(Player* player) { player->getHostileRefManager().setOnlineOfflineState(false); player->AddUnitState(UNIT_STATE_IN_FLIGHT); - player->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT); + player->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_TAXI_FLIGHT); Movement::MoveSplineInit init(player); uint32 end = GetPathAtMapEnd(); diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h index 1dd4611d53b..72309822dab 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h @@ -28,9 +28,9 @@ #include "MovementGenerator.h" #include "WaypointManager.h" #include "Player.h" +#include "World.h" #define FLIGHT_TRAVEL_UPDATE 100 -#define STOP_TIME_FOR_PLAYER 3 * MINUTE * IN_MILLISECONDS // 3 Minutes #define TIMEDIFF_NEXT_WP 250 template<class T, class P> diff --git a/src/server/game/Movement/PathGenerator.cpp b/src/server/game/Movement/PathGenerator.cpp index 3b4f19adb0b..3f8e7d44ff2 100644 --- a/src/server/game/Movement/PathGenerator.cpp +++ b/src/server/game/Movement/PathGenerator.cpp @@ -25,6 +25,7 @@ #include "DisableMgr.h" #include "DetourCommon.h" #include "DetourNavMeshQuery.h" +#include "Metric.h" ////////////////// PathGenerator ////////////////// PathGenerator::PathGenerator(const Unit* owner) : @@ -61,6 +62,8 @@ bool PathGenerator::CalculatePath(float destX, float destY, float destZ, bool fo if (!Trinity::IsValidMapCoord(destX, destY, destZ) || !Trinity::IsValidMapCoord(x, y, z)) return false; + TC_METRIC_EVENT("mmap_events", "CalculatePath", ""); + G3D::Vector3 dest(destX, destY, destZ); SetEndPosition(dest); @@ -939,3 +942,8 @@ void PathGenerator::ReducePathLenghtByDist(float dist) nextVec = currVec; // we're going backwards } } + +bool PathGenerator::IsInvalidDestinationZ(Unit const* target) const +{ + return (target->GetPositionZ() - GetActualEndPosition().z) > 5.0f; +} diff --git a/src/server/game/Movement/PathGenerator.h b/src/server/game/Movement/PathGenerator.h index 71e0e88f0b2..a3e88b8a705 100644 --- a/src/server/game/Movement/PathGenerator.h +++ b/src/server/game/Movement/PathGenerator.h @@ -49,7 +49,7 @@ enum PathType PATHFIND_SHORT = 0x20, // path is longer or equal to its limited path length }; -class PathGenerator +class TC_GAME_API PathGenerator { public: explicit PathGenerator(Unit const* owner); @@ -58,6 +58,7 @@ class PathGenerator // Calculate the path from owner to given destination // return: true if new path was calculated, false otherwise (no change needed) bool CalculatePath(float destX, float destY, float destZ, bool forceDest = false, bool straightLine = false); + bool IsInvalidDestinationZ(Unit const* target) const; // option setters - use optional void SetUseStraightPath(bool useStraightPath) { _useStraightPath = useStraightPath; } diff --git a/src/server/game/Movement/Spline/MoveSpline.cpp b/src/server/game/Movement/Spline/MoveSpline.cpp index d8173aab331..991a4eacd29 100644 --- a/src/server/game/Movement/Spline/MoveSpline.cpp +++ b/src/server/game/Movement/Spline/MoveSpline.cpp @@ -206,7 +206,7 @@ bool MoveSplineInitArgs::Validate(Unit* unit) const return false;\ } CHECK(path.size() > 1); - CHECK(velocity > 0.1f); + CHECK(velocity > 0.01f); CHECK(time_perc >= 0.f && time_perc <= 1.f); //CHECK(_checkPathBounds()); return true; diff --git a/src/server/game/Movement/Spline/MoveSpline.h b/src/server/game/Movement/Spline/MoveSpline.h index 209f978d658..0e62862cecc 100644 --- a/src/server/game/Movement/Spline/MoveSpline.h +++ b/src/server/game/Movement/Spline/MoveSpline.h @@ -37,7 +37,7 @@ namespace Movement // MoveSpline represents smooth catmullrom or linear curve and point that moves belong it // curve can be cyclic - in this case movement will be cyclic // point can have vertical acceleration motion componemt(used in fall, parabolic movement) - class MoveSpline + class TC_GAME_API MoveSpline { public: typedef Spline<int32> MySpline; diff --git a/src/server/game/Movement/Spline/MoveSplineInit.h b/src/server/game/Movement/Spline/MoveSplineInit.h index a94c84d92f3..3f38da97916 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.h +++ b/src/server/game/Movement/Spline/MoveSplineInit.h @@ -35,7 +35,7 @@ namespace Movement }; // Transforms coordinates from global to transport offsets - class TransportPathTransform + class TC_GAME_API TransportPathTransform { public: TransportPathTransform(Unit* owner, bool transformForTransport) @@ -49,7 +49,7 @@ namespace Movement /* Initializes and launches spline movement */ - class MoveSplineInit + class TC_GAME_API MoveSplineInit { public: diff --git a/src/server/game/Movement/Spline/MovementTypedefs.h b/src/server/game/Movement/Spline/MovementTypedefs.h index 031ec729949..c87fea47a82 100644 --- a/src/server/game/Movement/Spline/MovementTypedefs.h +++ b/src/server/game/Movement/Spline/MovementTypedefs.h @@ -69,8 +69,8 @@ namespace Movement typedef counter<uint32, 0xFFFFFFFF> UInt32Counter; - extern float gravity; - extern UInt32Counter splineIdGen; + TC_GAME_API extern float gravity; + TC_GAME_API extern UInt32Counter splineIdGen; } #endif // TRINITYSERVER_TYPEDEFS_H diff --git a/src/server/game/Movement/Waypoints/WaypointManager.cpp b/src/server/game/Movement/Waypoints/WaypointManager.cpp index e0639e38e77..dc935263927 100644 --- a/src/server/game/Movement/Waypoints/WaypointManager.cpp +++ b/src/server/game/Movement/Waypoints/WaypointManager.cpp @@ -94,6 +94,12 @@ void WaypointMgr::Load() TC_LOG_INFO("server.loading", ">> Loaded %u waypoints in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } +WaypointMgr* WaypointMgr::instance() +{ + static WaypointMgr instance; + return &instance; +} + void WaypointMgr::ReloadPath(uint32 id) { WaypointPathContainer::iterator itr = _waypointStore.find(id); diff --git a/src/server/game/Movement/Waypoints/WaypointManager.h b/src/server/game/Movement/Waypoints/WaypointManager.h index d519eee4793..63dc4184308 100644 --- a/src/server/game/Movement/Waypoints/WaypointManager.h +++ b/src/server/game/Movement/Waypoints/WaypointManager.h @@ -44,14 +44,10 @@ struct WaypointData typedef std::vector<WaypointData*> WaypointPath; typedef std::unordered_map<uint32, WaypointPath> WaypointPathContainer; -class WaypointMgr +class TC_GAME_API WaypointMgr { public: - static WaypointMgr* instance() - { - static WaypointMgr instance; - return &instance; - } + static WaypointMgr* instance(); // Attempts to reload a single path from database void ReloadPath(uint32 id); diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index d329ab27de9..1343e0966c1 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -95,7 +95,7 @@ void OPvPCapturePoint::AddGO(uint32 type, ObjectGuid::LowType guid, uint32 entry entry = data->id; } - m_Objects[type] = ObjectGuid(HighGuid::GameObject, entry, guid); + m_Objects[type] = guid; m_ObjectTypes[m_Objects[type]] = type; } @@ -109,7 +109,7 @@ void OPvPCapturePoint::AddCre(uint32 type, ObjectGuid::LowType guid, uint32 entr entry = data->id; } - m_Creatures[type] = ObjectGuid(HighGuid::Unit, entry, guid); + m_Creatures[type] = guid; m_CreatureTypes[m_Creatures[type]] = type; } @@ -190,7 +190,8 @@ bool OPvPCapturePoint::DelCreature(uint32 type) // delete respawn time for this creature PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); stmt->setUInt32(0, spawnId); - stmt->setUInt16(1, m_PvP->GetMap()->GetId()); stmt->setUInt32(2, 0); // instance id, always 0 for world maps + stmt->setUInt16(1, m_PvP->GetMap()->GetId()); + stmt->setUInt32(2, 0); // instance id, always 0 for world maps CharacterDatabase.Execute(stmt); sObjectMgr->DeleteCreatureData(spawnId); @@ -236,9 +237,9 @@ bool OPvPCapturePoint::DelCapturePoint() void OPvPCapturePoint::DeleteSpawns() { - for (std::map<uint32, uint32>::iterator i = m_Objects.begin(); i != m_Objects.end(); ++i) + for (std::map<uint32, ObjectGuid::LowType>::iterator i = m_Objects.begin(); i != m_Objects.end(); ++i) DelObject(i->first); - for (std::map<uint32, uint32>::iterator i = m_Creatures.begin(); i != m_Creatures.end(); ++i) + for (std::map<uint32, ObjectGuid::LowType>::iterator i = m_Creatures.begin(); i != m_Creatures.end(); ++i) DelCreature(i->first); DelCapturePoint(); } @@ -581,7 +582,7 @@ bool OPvPCapturePoint::HandleDropFlag(Player* /*player*/, uint32 /*id*/) int32 OPvPCapturePoint::HandleOpenGo(Player* /*player*/, GameObject* go) { - std::map<uint32, uint32>::iterator itr = m_ObjectTypes.find(go->GetSpawnId()); + std::map<ObjectGuid::LowType, uint32>::iterator itr = m_ObjectTypes.find(go->GetSpawnId()); if (itr != m_ObjectTypes.end()) return itr->second; @@ -596,7 +597,7 @@ bool OutdoorPvP::HandleAreaTrigger(Player* /*player*/, uint32 /*trigger*/) void OutdoorPvP::BroadcastPacket(WorldPacket &data) const { // This is faster than sWorld->SendZoneMessage - for (uint32 team = 0; team < 2; ++team) + for (uint32 team = 0; team < BG_TEAMS_COUNT; ++team) for (GuidSet::const_iterator itr = m_players[team].begin(); itr != m_players[team].end(); ++itr) if (Player* const player = ObjectAccessor::FindPlayer(*itr)) player->GetSession()->SendPacket(&data); diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index 79f34ff10ea..255f3cd0f99 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -84,7 +84,7 @@ class Unit; struct GossipMenuItems; class OutdoorPvP; -class OPvPCapturePoint +class TC_GAME_API OPvPCapturePoint { public: @@ -185,7 +185,7 @@ class OPvPCapturePoint }; // base class for specific outdoor pvp handlers -class OutdoorPvP : public ZoneScript +class TC_GAME_API OutdoorPvP : public ZoneScript { friend class OutdoorPvPMgr; diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp index 8296cdfb7ea..aa00d211d6e 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -33,8 +33,20 @@ void OutdoorPvPMgr::Die() for (OutdoorPvPSet::iterator itr = m_OutdoorPvPSet.begin(); itr != m_OutdoorPvPSet.end(); ++itr) delete *itr; + m_OutdoorPvPSet.clear(); + for (OutdoorPvPDataMap::iterator itr = m_OutdoorPvPDatas.begin(); itr != m_OutdoorPvPDatas.end(); ++itr) delete itr->second; + + m_OutdoorPvPDatas.clear(); + + m_OutdoorPvPMap.clear(); +} + +OutdoorPvPMgr* OutdoorPvPMgr::instance() +{ + static OutdoorPvPMgr instance; + return &instance; } void OutdoorPvPMgr::InitOutdoorPvP() diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h index 8a113987882..e53a78ac271 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h @@ -35,18 +35,14 @@ struct OutdoorPvPData }; // class to handle player enter / leave / areatrigger / GO use events -class OutdoorPvPMgr +class TC_GAME_API OutdoorPvPMgr { private: OutdoorPvPMgr(); ~OutdoorPvPMgr() { }; public: - static OutdoorPvPMgr* instance() - { - static OutdoorPvPMgr instance; - return &instance; - } + static OutdoorPvPMgr* instance(); // create outdoor pvp events void InitOutdoorPvP(); diff --git a/src/server/game/Pools/PoolMgr.cpp b/src/server/game/Pools/PoolMgr.cpp index 12fb8a06b62..812d8ea3940 100644 --- a/src/server/game/Pools/PoolMgr.cpp +++ b/src/server/game/Pools/PoolMgr.cpp @@ -60,6 +60,11 @@ bool ActivePoolData::IsActiveObject<Quest>(uint32 quest_id) const return mActiveQuests.find(quest_id) != mActiveQuests.end(); } +template TC_GAME_API bool ActivePoolData::IsActiveObject<Creature>(uint32) const; +template TC_GAME_API bool ActivePoolData::IsActiveObject<GameObject>(uint32) const; +template TC_GAME_API bool ActivePoolData::IsActiveObject<Pool>(uint32) const; +template TC_GAME_API bool ActivePoolData::IsActiveObject<Quest>(uint32) const; + template<> void ActivePoolData::ActivateObject<Creature>(uint32 db_guid, uint32 pool_id) { @@ -570,6 +575,12 @@ void PoolMgr::Initialize() mCreatureSearchMap.clear(); } +PoolMgr* PoolMgr::instance() +{ + static PoolMgr instance; + return &instance; +} + void PoolMgr::LoadFromDB() { // Pool templates diff --git a/src/server/game/Pools/PoolMgr.h b/src/server/game/Pools/PoolMgr.h index 51e0bcb4cac..f1af3a3530e 100644 --- a/src/server/game/Pools/PoolMgr.h +++ b/src/server/game/Pools/PoolMgr.h @@ -43,7 +43,7 @@ class Pool // for Pool of Pool typedef std::set<ObjectGuid::LowType> ActivePoolObjects; typedef std::map<uint32, uint32> ActivePoolPools; -class ActivePoolData +class TC_GAME_API ActivePoolData { public: template<typename T> @@ -66,7 +66,7 @@ class ActivePoolData }; template <class T> -class PoolGroup +class TC_GAME_API PoolGroup { typedef std::vector<PoolObject> PoolObjectList; public: @@ -101,18 +101,14 @@ typedef std::multimap<uint32, uint32> PooledQuestRelation; typedef std::pair<PooledQuestRelation::const_iterator, PooledQuestRelation::const_iterator> PooledQuestRelationBounds; typedef std::pair<PooledQuestRelation::iterator, PooledQuestRelation::iterator> PooledQuestRelationBoundsNC; -class PoolMgr +class TC_GAME_API PoolMgr { private: PoolMgr(); ~PoolMgr() { }; public: - static PoolMgr* instance() - { - static PoolMgr instance; - return &instance; - } + static PoolMgr* instance(); void LoadFromDB(); void LoadQuestPools(); diff --git a/src/server/game/Quests/QuestDef.cpp b/src/server/game/Quests/QuestDef.cpp index 4a4ee9bff9c..91a7b87eec7 100644 --- a/src/server/game/Quests/QuestDef.cpp +++ b/src/server/game/Quests/QuestDef.cpp @@ -132,7 +132,15 @@ Quest::Quest(Field* questRecord) void Quest::LoadQuestDetails(Field* fields) { for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) + { + if (!sEmotesStore.LookupEntry(fields[1+i].GetUInt16())) + { + TC_LOG_ERROR("sql.sql", "Table `quest_details` has non-existing Emote%i (%u) set for quest %u. Skipped.", 1+i, fields[1+i].GetUInt16(), fields[0].GetUInt32()); + continue; + } + DetailsEmote[i] = fields[1+i].GetUInt16(); + } for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) DetailsEmoteDelay[i] = fields[5+i].GetUInt32(); @@ -142,13 +150,28 @@ void Quest::LoadQuestRequestItems(Field* fields) { EmoteOnComplete = fields[1].GetUInt16(); EmoteOnIncomplete = fields[2].GetUInt16(); + + if (!sEmotesStore.LookupEntry(EmoteOnComplete)) + TC_LOG_ERROR("sql.sql", "Table `quest_request_items` has non-existing EmoteOnComplete (%u) set for quest %u.", EmoteOnComplete, fields[0].GetUInt32()); + + if (!sEmotesStore.LookupEntry(EmoteOnIncomplete)) + TC_LOG_ERROR("sql.sql", "Table `quest_request_items` has non-existing EmoteOnIncomplete (%u) set for quest %u.", EmoteOnIncomplete, fields[0].GetUInt32()); + RequestItemsText = fields[3].GetString(); } void Quest::LoadQuestOfferReward(Field* fields) { for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) + { + if (!sEmotesStore.LookupEntry(fields[1+i].GetUInt16())) + { + TC_LOG_ERROR("sql.sql", "Table `quest_offer_reward` has non-existing Emote%i (%u) set for quest %u. Skipped.", 1+i, fields[1+i].GetUInt16(), fields[0].GetUInt32()); + continue; + } + OfferRewardEmote[i] = fields[1+i].GetUInt16(); + } for (int i = 0; i < QUEST_EMOTE_COUNT; ++i) OfferRewardEmoteDelay[i] = fields[5+i].GetUInt32(); @@ -173,7 +196,8 @@ void Quest::LoadQuestTemplateAddon(Field* fields) RequiredMinRepValue = fields[13].GetInt32(); RequiredMaxRepValue = fields[14].GetInt32(); StartItemCount = fields[15].GetUInt8(); - SpecialFlags = fields[16].GetUInt8(); + RewardMailSenderEntry = fields[16].GetUInt32(); + SpecialFlags = fields[17].GetUInt8(); if (SpecialFlags & QUEST_SPECIAL_FLAGS_AUTO_ACCEPT) Flags |= QUEST_FLAGS_AUTO_ACCEPT; @@ -254,6 +278,9 @@ bool Quest::IsRaidQuest(Difficulty difficulty) const break; } + if ((Flags & QUEST_FLAGS_RAID) != 0) + return true; + return false; } @@ -285,3 +312,10 @@ uint32 Quest::CalculateHonorGain(uint8 level) const return honor; } + +bool Quest::CanIncreaseRewardedQuestCounters() const +{ + // Dungeon Finder/Daily/Repeatable (if not weekly, monthly or seasonal) quests are never considered rewarded serverside. + // This affects counters and client requests for completed quests. + return (!IsDFQuest() && !IsDaily() && (!IsRepeatable() || IsWeekly() || IsMonthly() || IsSeasonal())); +} diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index a502fef6140..dc6d22deab0 100644 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -60,7 +60,7 @@ enum QuestFailedReason INVALIDREASON_DAILY_QUEST_COMPLETED_TODAY = 29 // You have completed that daily quest today. }; -enum QuestShareMessages +enum QuestShareMessages : uint8 { QUEST_PARTY_MSG_SHARING_QUEST = 0, QUEST_PARTY_MSG_CANT_TAKE_QUEST = 1, @@ -134,7 +134,7 @@ enum QuestFlags QUEST_FLAGS_SHARABLE = 0x00000008, // Can be shared: Player::CanShareQuest() QUEST_FLAGS_HAS_CONDITION = 0x00000010, // Not used currently QUEST_FLAGS_HIDE_REWARD_POI = 0x00000020, // Not used currently: Unsure of content - QUEST_FLAGS_RAID = 0x00000040, // Not used currently + QUEST_FLAGS_RAID = 0x00000040, // Can be completed while in raid QUEST_FLAGS_TBC = 0x00000080, // Not used currently: Available if TBC expansion enabled only QUEST_FLAGS_NO_MONEY_FROM_XP = 0x00000100, // Not used currently: Experience is not converted to gold at max level QUEST_FLAGS_HIDDEN_REWARDS = 0x00000200, // Items and money rewarded only sent in SMSG_QUESTGIVER_OFFER_REWARD (not in SMSG_QUESTGIVER_QUEST_DETAILS or in client quest log(SMSG_QUEST_QUERY_RESPONSE)) @@ -190,7 +190,7 @@ struct QuestLocale // This Quest class provides a convenient way to access a few pretotaled (cached) quest details, // all base quest information, and any utility functions such as generating the amount of // xp to give -class Quest +class TC_GAME_API Quest { friend class ObjectMgr; public: @@ -257,6 +257,7 @@ class Quest int32 GetRewSpellCast() const { return RewardSpell; } uint32 GetRewMailTemplateId() const { return RewardMailTemplateId; } uint32 GetRewMailDelaySecs() const { return RewardMailDelay; } + uint32 GetRewMailSenderEntry() const { return RewardMailSenderEntry; } uint32 GetPOIContinent() const { return POIContinent; } float GetPOIx() const { return POIx; } float GetPOIy() const { return POIy; } @@ -276,6 +277,7 @@ class Quest bool IsAllowedInRaid(Difficulty difficulty) const; bool IsDFQuest() const { return (SpecialFlags & QUEST_SPECIAL_FLAGS_DF_QUEST) != 0; } uint32 CalculateHonorGain(uint8 level) const; + bool CanIncreaseRewardedQuestCounters() const; // multiple values std::string ObjectiveText[QUEST_OBJECTIVES_COUNT]; @@ -373,6 +375,7 @@ class Quest uint32 RequiredMaxRepFaction = 0; int32 RequiredMaxRepValue = 0; uint32 StartItemCount = 0; + uint32 RewardMailSenderEntry = 0; uint32 SpecialFlags = 0; // custom flags, not sniffed/WDB }; diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index 6f319a39b0c..5a51c9eb383 100644 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -61,7 +61,7 @@ typedef std::map<uint32, ReputationRank> ForcedReactions; class Player; -class ReputationMgr +class TC_GAME_API ReputationMgr { public: // constructors and global modifiers explicit ReputationMgr(Player* owner) : _player(owner), diff --git a/src/server/game/Scripting/ScriptLoader.cpp b/src/server/game/Scripting/ScriptLoader.cpp deleted file mode 100644 index 2922e4ef58d..00000000000 --- a/src/server/game/Scripting/ScriptLoader.cpp +++ /dev/null @@ -1,1421 +0,0 @@ -/* - * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "ScriptLoader.h" -#include "World.h" - -// spells -void AddSC_deathknight_spell_scripts(); -void AddSC_druid_spell_scripts(); -void AddSC_generic_spell_scripts(); -void AddSC_hunter_spell_scripts(); -void AddSC_mage_spell_scripts(); -void AddSC_paladin_spell_scripts(); -void AddSC_priest_spell_scripts(); -void AddSC_rogue_spell_scripts(); -void AddSC_shaman_spell_scripts(); -void AddSC_warlock_spell_scripts(); -void AddSC_warrior_spell_scripts(); -void AddSC_quest_spell_scripts(); -void AddSC_item_spell_scripts(); -void AddSC_holiday_spell_scripts(); - -void AddSC_SmartScripts(); - -//Commands -void AddSC_account_commandscript(); -void AddSC_achievement_commandscript(); -void AddSC_ahbot_commandscript(); -void AddSC_arena_commandscript(); -void AddSC_ban_commandscript(); -void AddSC_bf_commandscript(); -void AddSC_cast_commandscript(); -void AddSC_character_commandscript(); -void AddSC_cheat_commandscript(); -void AddSC_debug_commandscript(); -void AddSC_deserter_commandscript(); -void AddSC_disable_commandscript(); -void AddSC_event_commandscript(); -void AddSC_gm_commandscript(); -void AddSC_go_commandscript(); -void AddSC_gobject_commandscript(); -void AddSC_group_commandscript(); -void AddSC_guild_commandscript(); -void AddSC_honor_commandscript(); -void AddSC_instance_commandscript(); -void AddSC_learn_commandscript(); -void AddSC_lfg_commandscript(); -void AddSC_list_commandscript(); -void AddSC_lookup_commandscript(); -void AddSC_message_commandscript(); -void AddSC_misc_commandscript(); -void AddSC_mmaps_commandscript(); -void AddSC_modify_commandscript(); -void AddSC_npc_commandscript(); -void AddSC_pet_commandscript(); -void AddSC_quest_commandscript(); -void AddSC_rbac_commandscript(); -void AddSC_reload_commandscript(); -void AddSC_reset_commandscript(); -void AddSC_send_commandscript(); -void AddSC_server_commandscript(); -void AddSC_tele_commandscript(); -void AddSC_ticket_commandscript(); -void AddSC_titles_commandscript(); -void AddSC_wp_commandscript(); - -#ifdef SCRIPTS -//world -void AddSC_areatrigger_scripts(); -void AddSC_emerald_dragons(); -void AddSC_generic_creature(); -void AddSC_go_scripts(); -void AddSC_guards(); -void AddSC_item_scripts(); -void AddSC_npc_professions(); -void AddSC_npc_innkeeper(); -void AddSC_npcs_special(); -void AddSC_achievement_scripts(); -void AddSC_action_ip_logger(); -void AddSC_duel_reset(); - -//eastern kingdoms -void AddSC_alterac_valley(); //Alterac Valley -void AddSC_boss_balinda(); -void AddSC_boss_drekthar(); -void AddSC_boss_galvangar(); -void AddSC_boss_vanndar(); -void AddSC_blackrock_depths(); //Blackrock Depths -void AddSC_boss_ambassador_flamelash(); -void AddSC_boss_draganthaurissan(); -void AddSC_boss_general_angerforge(); -void AddSC_boss_high_interrogator_gerstahn(); -void AddSC_boss_magmus(); -void AddSC_boss_moira_bronzebeard(); -void AddSC_boss_tomb_of_seven(); -void AddSC_instance_blackrock_depths(); -void AddSC_boss_drakkisath(); //Blackrock Spire -void AddSC_boss_halycon(); -void AddSC_boss_highlordomokk(); -void AddSC_boss_mothersmolderweb(); -void AddSC_boss_overlordwyrmthalak(); -void AddSC_boss_shadowvosh(); -void AddSC_boss_thebeast(); -void AddSC_boss_warmastervoone(); -void AddSC_boss_quatermasterzigris(); -void AddSC_boss_pyroguard_emberseer(); -void AddSC_boss_gyth(); -void AddSC_boss_rend_blackhand(); -void AddSC_boss_gizrul_the_slavener(); -void AddSC_boss_urok_doomhowl(); -void AddSC_boss_lord_valthalak(); -void AddSC_instance_blackrock_spire(); -void AddSC_boss_razorgore(); //Blackwing lair -void AddSC_boss_vaelastrasz(); -void AddSC_boss_broodlord(); -void AddSC_boss_firemaw(); -void AddSC_boss_ebonroc(); -void AddSC_boss_flamegor(); -void AddSC_boss_chromaggus(); -void AddSC_boss_nefarian(); -void AddSC_instance_blackwing_lair(); -void AddSC_deadmines(); //Deadmines -void AddSC_instance_deadmines(); -void AddSC_boss_mr_smite(); -void AddSC_gnomeregan(); //Gnomeregan -void AddSC_instance_gnomeregan(); -void AddSC_boss_attumen(); //Karazhan -void AddSC_boss_curator(); -void AddSC_boss_maiden_of_virtue(); -void AddSC_boss_shade_of_aran(); -void AddSC_boss_malchezaar(); -void AddSC_boss_terestian_illhoof(); -void AddSC_boss_moroes(); -void AddSC_bosses_opera(); -void AddSC_boss_netherspite(); -void AddSC_instance_karazhan(); -void AddSC_karazhan(); -void AddSC_boss_nightbane(); -void AddSC_boss_felblood_kaelthas(); // Magister's Terrace -void AddSC_boss_selin_fireheart(); -void AddSC_boss_vexallus(); -void AddSC_boss_priestess_delrissa(); -void AddSC_instance_magisters_terrace(); -void AddSC_magisters_terrace(); -void AddSC_boss_lucifron(); //Molten core -void AddSC_boss_magmadar(); -void AddSC_boss_gehennas(); -void AddSC_boss_garr(); -void AddSC_boss_baron_geddon(); -void AddSC_boss_shazzrah(); -void AddSC_boss_golemagg(); -void AddSC_boss_sulfuron(); -void AddSC_boss_majordomo(); -void AddSC_boss_ragnaros(); -void AddSC_instance_molten_core(); -void AddSC_instance_ragefire_chasm(); //Ragefire Chasm -void AddSC_the_scarlet_enclave(); //Scarlet Enclave -void AddSC_the_scarlet_enclave_c1(); -void AddSC_the_scarlet_enclave_c2(); -void AddSC_the_scarlet_enclave_c5(); -void AddSC_boss_arcanist_doan(); //Scarlet Monastery -void AddSC_boss_azshir_the_sleepless(); -void AddSC_boss_bloodmage_thalnos(); -void AddSC_boss_headless_horseman(); -void AddSC_boss_herod(); -void AddSC_boss_high_inquisitor_fairbanks(); -void AddSC_boss_houndmaster_loksey(); -void AddSC_boss_interrogator_vishas(); -void AddSC_boss_scorn(); -void AddSC_instance_scarlet_monastery(); -void AddSC_boss_mograine_and_whitemane(); -void AddSC_boss_darkmaster_gandling(); //Scholomance -void AddSC_boss_death_knight_darkreaver(); -void AddSC_boss_theolenkrastinov(); -void AddSC_boss_illuciabarov(); -void AddSC_boss_instructormalicia(); -void AddSC_boss_jandicebarov(); -void AddSC_boss_kormok(); -void AddSC_boss_lordalexeibarov(); -void AddSC_boss_lorekeeperpolkelt(); -void AddSC_boss_rasfrost(); -void AddSC_boss_theravenian(); -void AddSC_boss_vectus(); -void AddSC_boss_kirtonos_the_herald(); -void AddSC_instance_scholomance(); -void AddSC_shadowfang_keep(); //Shadowfang keep -void AddSC_instance_shadowfang_keep(); -void AddSC_boss_magistrate_barthilas(); //Stratholme -void AddSC_boss_maleki_the_pallid(); -void AddSC_boss_nerubenkan(); -void AddSC_boss_cannon_master_willey(); -void AddSC_boss_baroness_anastari(); -void AddSC_boss_ramstein_the_gorger(); -void AddSC_boss_timmy_the_cruel(); -void AddSC_boss_postmaster_malown(); -void AddSC_boss_baron_rivendare(); -void AddSC_boss_dathrohan_balnazzar(); -void AddSC_boss_order_of_silver_hand(); -void AddSC_instance_stratholme(); -void AddSC_stratholme(); -void AddSC_sunken_temple(); // Sunken Temple -void AddSC_instance_sunken_temple(); -void AddSC_instance_sunwell_plateau(); //Sunwell Plateau -void AddSC_boss_kalecgos(); -void AddSC_boss_brutallus(); -void AddSC_boss_felmyst(); -void AddSC_boss_eredar_twins(); -void AddSC_boss_muru(); -void AddSC_boss_kiljaeden(); -void AddSC_sunwell_plateau(); -void AddSC_boss_archaedas(); //Uldaman -void AddSC_boss_ironaya(); -void AddSC_uldaman(); -void AddSC_instance_uldaman(); -void AddSC_instance_the_stockade(); //The Stockade -void AddSC_boss_akilzon(); //Zul'Aman -void AddSC_boss_halazzi(); -void AddSC_boss_hex_lord_malacrass(); -void AddSC_boss_janalai(); -void AddSC_boss_nalorakk(); -void AddSC_boss_zuljin(); -void AddSC_instance_zulaman(); -void AddSC_zulaman(); -void AddSC_boss_jeklik(); //Zul'Gurub -void AddSC_boss_venoxis(); -void AddSC_boss_marli(); -void AddSC_boss_mandokir(); -void AddSC_boss_gahzranka(); -void AddSC_boss_thekal(); -void AddSC_boss_arlokk(); -void AddSC_boss_jindo(); -void AddSC_boss_hakkar(); -void AddSC_boss_grilek(); -void AddSC_boss_hazzarah(); -void AddSC_boss_renataki(); -void AddSC_boss_wushoolay(); -void AddSC_instance_zulgurub(); - -//void AddSC_alterac_mountains(); -void AddSC_arathi_highlands(); -void AddSC_blasted_lands(); -void AddSC_burning_steppes(); -void AddSC_duskwood(); -void AddSC_eastern_plaguelands(); -void AddSC_ghostlands(); -void AddSC_hinterlands(); -void AddSC_isle_of_queldanas(); -void AddSC_loch_modan(); -void AddSC_redridge_mountains(); -void AddSC_silverpine_forest(); -void AddSC_stormwind_city(); -void AddSC_stranglethorn_vale(); -void AddSC_swamp_of_sorrows(); -void AddSC_tirisfal_glades(); -void AddSC_undercity(); -void AddSC_western_plaguelands(); -void AddSC_wetlands(); - -//kalimdor -void AddSC_blackfathom_deeps(); //Blackfathom Depths -void AddSC_boss_gelihast(); -void AddSC_boss_kelris(); -void AddSC_boss_aku_mai(); -void AddSC_instance_blackfathom_deeps(); -void AddSC_hyjal(); //CoT Battle for Mt. Hyjal -void AddSC_boss_archimonde(); -void AddSC_instance_mount_hyjal(); -void AddSC_hyjal_trash(); -void AddSC_boss_rage_winterchill(); -void AddSC_boss_anetheron(); -void AddSC_boss_kazrogal(); -void AddSC_boss_azgalor(); -void AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad -void AddSC_boss_epoch_hunter(); -void AddSC_boss_lieutenant_drake(); -void AddSC_instance_old_hillsbrad(); -void AddSC_old_hillsbrad(); -void AddSC_boss_aeonus(); //CoT The Black Morass -void AddSC_boss_chrono_lord_deja(); -void AddSC_boss_temporus(); -void AddSC_the_black_morass(); -void AddSC_instance_the_black_morass(); -void AddSC_boss_epoch(); //CoT Culling Of Stratholme -void AddSC_boss_infinite_corruptor(); -void AddSC_boss_salramm(); -void AddSC_boss_mal_ganis(); -void AddSC_boss_meathook(); -void AddSC_culling_of_stratholme(); -void AddSC_instance_culling_of_stratholme(); -void AddSC_instance_dire_maul(); //Dire Maul -void AddSC_boss_celebras_the_cursed(); //Maraudon -void AddSC_boss_landslide(); -void AddSC_boss_noxxion(); -void AddSC_boss_ptheradras(); -void AddSC_instance_maraudon(); -void AddSC_boss_onyxia(); //Onyxia's Lair -void AddSC_instance_onyxias_lair(); -void AddSC_boss_tuten_kash(); //Razorfen Downs -void AddSC_boss_mordresh_fire_eye(); -void AddSC_boss_glutton(); -void AddSC_boss_amnennar_the_coldbringer(); -void AddSC_razorfen_downs(); -void AddSC_instance_razorfen_downs(); -void AddSC_razorfen_kraul(); //Razorfen Kraul -void AddSC_instance_razorfen_kraul(); -void AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj -void AddSC_boss_rajaxx(); -void AddSC_boss_moam(); -void AddSC_boss_buru(); -void AddSC_boss_ayamiss(); -void AddSC_boss_ossirian(); -void AddSC_instance_ruins_of_ahnqiraj(); -void AddSC_boss_cthun(); //Temple of ahn'qiraj -void AddSC_boss_viscidus(); -void AddSC_boss_fankriss(); -void AddSC_boss_huhuran(); -void AddSC_bug_trio(); -void AddSC_boss_sartura(); -void AddSC_boss_skeram(); -void AddSC_boss_twinemperors(); -void AddSC_boss_ouro(); -void AddSC_npc_anubisath_sentinel(); -void AddSC_instance_temple_of_ahnqiraj(); -void AddSC_wailing_caverns(); //Wailing caverns -void AddSC_instance_wailing_caverns(); -void AddSC_boss_zum_rah(); //Zul'Farrak -void AddSC_zulfarrak(); -void AddSC_instance_zulfarrak(); - -void AddSC_ashenvale(); -void AddSC_azshara(); -void AddSC_azuremyst_isle(); -void AddSC_bloodmyst_isle(); -void AddSC_boss_azuregos(); -void AddSC_darkshore(); -void AddSC_desolace(); -void AddSC_durotar(); -void AddSC_dustwallow_marsh(); -void AddSC_felwood(); -void AddSC_feralas(); -void AddSC_moonglade(); -void AddSC_orgrimmar(); -void AddSC_silithus(); -void AddSC_stonetalon_mountains(); -void AddSC_tanaris(); -void AddSC_the_barrens(); -void AddSC_thousand_needles(); -void AddSC_thunder_bluff(); -void AddSC_ungoro_crater(); -void AddSC_winterspring(); - -// Northrend - -void AddSC_boss_slad_ran(); -void AddSC_boss_moorabi(); -void AddSC_boss_drakkari_colossus(); -void AddSC_boss_gal_darah(); -void AddSC_boss_eck(); -void AddSC_instance_gundrak(); - -// Azjol-Nerub - Azjol-Nerub -void AddSC_boss_krik_thir(); -void AddSC_boss_hadronox(); -void AddSC_boss_anub_arak(); -void AddSC_instance_azjol_nerub(); - -// Azjol-Nerub - Ahn'kahet -void AddSC_boss_elder_nadox(); -void AddSC_boss_taldaram(); -void AddSC_boss_amanitar(); -void AddSC_boss_jedoga_shadowseeker(); -void AddSC_boss_volazj(); -void AddSC_instance_ahnkahet(); - -// Drak'Tharon Keep -void AddSC_boss_trollgore(); -void AddSC_boss_novos(); -void AddSC_boss_king_dred(); -void AddSC_boss_tharon_ja(); -void AddSC_instance_drak_tharon_keep(); - -void AddSC_boss_argent_challenge(); //Trial of the Champion -void AddSC_boss_black_knight(); -void AddSC_boss_grand_champions(); -void AddSC_instance_trial_of_the_champion(); -void AddSC_trial_of_the_champion(); -void AddSC_boss_anubarak_trial(); //Trial of the Crusader -void AddSC_boss_faction_champions(); -void AddSC_boss_jaraxxus(); -void AddSC_boss_northrend_beasts(); -void AddSC_boss_twin_valkyr(); -void AddSC_trial_of_the_crusader(); -void AddSC_instance_trial_of_the_crusader(); -void AddSC_boss_anubrekhan(); //Naxxramas -void AddSC_boss_maexxna(); -void AddSC_boss_patchwerk(); -void AddSC_boss_grobbulus(); -void AddSC_boss_razuvious(); -void AddSC_boss_kelthuzad(); -void AddSC_boss_loatheb(); -void AddSC_boss_noth(); -void AddSC_boss_gluth(); -void AddSC_boss_sapphiron(); -void AddSC_boss_four_horsemen(); -void AddSC_boss_faerlina(); -void AddSC_boss_heigan(); -void AddSC_boss_gothik(); -void AddSC_boss_thaddius(); -void AddSC_instance_naxxramas(); -void AddSC_boss_nexus_commanders(); // The Nexus Nexus -void AddSC_boss_magus_telestra(); -void AddSC_boss_anomalus(); -void AddSC_boss_ormorok(); -void AddSC_boss_keristrasza(); -void AddSC_instance_nexus(); -void AddSC_boss_drakos(); //The Nexus The Oculus -void AddSC_boss_urom(); -void AddSC_boss_varos(); -void AddSC_boss_eregos(); -void AddSC_instance_oculus(); -void AddSC_oculus(); -void AddSC_boss_malygos(); // The Nexus: Eye of Eternity -void AddSC_instance_eye_of_eternity(); -void AddSC_boss_sartharion(); //Obsidian Sanctum -void AddSC_obsidian_sanctum(); -void AddSC_instance_obsidian_sanctum(); -void AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning -void AddSC_boss_loken(); -void AddSC_boss_ionar(); -void AddSC_boss_volkhan(); -void AddSC_instance_halls_of_lightning(); -void AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone -void AddSC_boss_krystallus(); -void AddSC_boss_sjonnir(); -void AddSC_instance_halls_of_stone(); -void AddSC_halls_of_stone(); -void AddSC_boss_auriaya(); //Ulduar Ulduar -void AddSC_boss_flame_leviathan(); -void AddSC_boss_ignis(); -void AddSC_boss_razorscale(); -void AddSC_boss_xt002(); -void AddSC_boss_kologarn(); -void AddSC_boss_assembly_of_iron(); -void AddSC_boss_general_vezax(); -void AddSC_boss_mimiron(); -void AddSC_boss_hodir(); -void AddSC_boss_freya(); -void AddSC_boss_yogg_saron(); -void AddSC_boss_algalon_the_observer(); -void AddSC_instance_ulduar(); - -// Utgarde Keep - Utgarde Keep -void AddSC_boss_keleseth(); -void AddSC_boss_skarvald_dalronn(); -void AddSC_boss_ingvar_the_plunderer(); -void AddSC_instance_utgarde_keep(); -void AddSC_utgarde_keep(); - -// Utgarde Keep - Utgarde Pinnacle -void AddSC_boss_svala(); -void AddSC_boss_palehoof(); -void AddSC_boss_skadi(); -void AddSC_boss_ymiron(); -void AddSC_instance_utgarde_pinnacle(); - -// Vault of Archavon -void AddSC_boss_archavon(); -void AddSC_boss_emalon(); -void AddSC_boss_koralon(); -void AddSC_boss_toravon(); -void AddSC_instance_vault_of_archavon(); - -void AddSC_boss_cyanigosa(); //Violet Hold -void AddSC_boss_erekem(); -void AddSC_boss_ichoron(); -void AddSC_boss_lavanthor(); -void AddSC_boss_moragg(); -void AddSC_boss_xevozz(); -void AddSC_boss_zuramat(); -void AddSC_instance_violet_hold(); -void AddSC_violet_hold(); -void AddSC_instance_forge_of_souls(); //Forge of Souls -void AddSC_forge_of_souls(); -void AddSC_boss_bronjahm(); -void AddSC_boss_devourer_of_souls(); -void AddSC_instance_pit_of_saron(); //Pit of Saron -void AddSC_pit_of_saron(); -void AddSC_boss_garfrost(); -void AddSC_boss_ick(); -void AddSC_boss_tyrannus(); -void AddSC_instance_halls_of_reflection(); // Halls of Reflection -void AddSC_halls_of_reflection(); -void AddSC_boss_falric(); -void AddSC_boss_marwyn(); -void AddSC_boss_lord_marrowgar(); // Icecrown Citadel -void AddSC_boss_lady_deathwhisper(); -void AddSC_boss_icecrown_gunship_battle(); -void AddSC_boss_deathbringer_saurfang(); -void AddSC_boss_festergut(); -void AddSC_boss_rotface(); -void AddSC_boss_professor_putricide(); -void AddSC_boss_blood_prince_council(); -void AddSC_boss_blood_queen_lana_thel(); -void AddSC_boss_valithria_dreamwalker(); -void AddSC_boss_sindragosa(); -void AddSC_boss_the_lich_king(); -void AddSC_icecrown_citadel_teleport(); -void AddSC_instance_icecrown_citadel(); -void AddSC_icecrown_citadel(); -void AddSC_instance_ruby_sanctum(); // Ruby Sanctum -void AddSC_ruby_sanctum(); -void AddSC_boss_baltharus_the_warborn(); -void AddSC_boss_saviana_ragefire(); -void AddSC_boss_general_zarithrian(); -void AddSC_boss_halion(); - -void AddSC_dalaran(); -void AddSC_borean_tundra(); -void AddSC_dragonblight(); -void AddSC_grizzly_hills(); -void AddSC_howling_fjord(); -void AddSC_icecrown(); -void AddSC_sholazar_basin(); -void AddSC_storm_peaks(); -void AddSC_wintergrasp(); -void AddSC_zuldrak(); -void AddSC_crystalsong_forest(); -void AddSC_isle_of_conquest(); - -// Outland - -// Auchindoun - Auchenai Crypts -void AddSC_boss_shirrak_the_dead_watcher(); -void AddSC_boss_exarch_maladaar(); -void AddSC_instance_auchenai_crypts(); - -// Auchindoun - Mana Tombs -void AddSC_boss_pandemonius(); -void AddSC_boss_nexusprince_shaffar(); -void AddSC_instance_mana_tombs(); - -// Auchindoun - Sekketh Halls -void AddSC_boss_darkweaver_syth(); -void AddSC_boss_talon_king_ikiss(); -void AddSC_boss_anzu(); -void AddSC_instance_sethekk_halls(); - -// Auchindoun - Shadow Labyrinth -void AddSC_boss_ambassador_hellmaw(); -void AddSC_boss_blackheart_the_inciter(); -void AddSC_boss_grandmaster_vorpil(); -void AddSC_boss_murmur(); -void AddSC_instance_shadow_labyrinth(); - -// Black Temple -void AddSC_black_temple(); -void AddSC_boss_illidan(); -void AddSC_boss_shade_of_akama(); -void AddSC_boss_supremus(); -void AddSC_boss_gurtogg_bloodboil(); -void AddSC_boss_mother_shahraz(); -void AddSC_boss_reliquary_of_souls(); -void AddSC_boss_teron_gorefiend(); -void AddSC_boss_najentus(); -void AddSC_boss_illidari_council(); -void AddSC_instance_black_temple(); - -// Coilfang Reservoir - Serpent Shrine Cavern -void AddSC_boss_fathomlord_karathress(); -void AddSC_boss_hydross_the_unstable(); -void AddSC_boss_lady_vashj(); -void AddSC_boss_leotheras_the_blind(); -void AddSC_boss_morogrim_tidewalker(); -void AddSC_instance_serpentshrine_cavern(); -void AddSC_boss_the_lurker_below(); - -// Coilfang Reservoir - The Steam Vault -void AddSC_boss_hydromancer_thespia(); -void AddSC_boss_mekgineer_steamrigger(); -void AddSC_boss_warlord_kalithresh(); -void AddSC_instance_steam_vault(); - -// Coilfang Reservoir - The Slave Pens -void AddSC_instance_the_slave_pens(); -void AddSC_boss_mennu_the_betrayer(); -void AddSC_boss_rokmar_the_crackler(); -void AddSC_boss_quagmirran(); - -// Coilfang Reservoir - The Underbog -void AddSC_instance_the_underbog(); -void AddSC_boss_hungarfen(); -void AddSC_boss_the_black_stalker(); - -// Gruul's Lair -void AddSC_boss_gruul(); -void AddSC_boss_high_king_maulgar(); -void AddSC_instance_gruuls_lair(); -void AddSC_boss_broggok(); //HC Blood Furnace -void AddSC_boss_kelidan_the_breaker(); -void AddSC_boss_the_maker(); -void AddSC_instance_blood_furnace(); -void AddSC_boss_magtheridon(); //HC Magtheridon's Lair -void AddSC_instance_magtheridons_lair(); -void AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls -void AddSC_boss_warbringer_omrogg(); -void AddSC_boss_warchief_kargath_bladefist(); -void AddSC_shattered_halls(); -void AddSC_instance_shattered_halls(); -void AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts -void AddSC_boss_omor_the_unscarred(); -void AddSC_boss_vazruden_the_herald(); -void AddSC_instance_ramparts(); -void AddSC_arcatraz(); //TK Arcatraz -void AddSC_boss_zereketh_the_unbound(); -void AddSC_boss_dalliah_the_doomsayer(); -void AddSC_boss_wrath_scryer_soccothrates(); -void AddSC_boss_harbinger_skyriss(); -void AddSC_instance_arcatraz(); -void AddSC_boss_high_botanist_freywinn(); //TK Botanica -void AddSC_boss_laj(); -void AddSC_boss_warp_splinter(); -void AddSC_boss_thorngrin_the_tender(); -void AddSC_boss_commander_sarannis(); -void AddSC_instance_the_botanica(); -void AddSC_boss_alar(); //TK The Eye -void AddSC_boss_kaelthas(); -void AddSC_boss_void_reaver(); -void AddSC_boss_high_astromancer_solarian(); -void AddSC_instance_the_eye(); -void AddSC_the_eye(); -void AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar -void AddSC_boss_gatewatcher_gyrokill(); -void AddSC_boss_nethermancer_sepethrea(); -void AddSC_boss_pathaleon_the_calculator(); -void AddSC_boss_mechano_lord_capacitus(); -void AddSC_instance_mechanar(); - -void AddSC_blades_edge_mountains(); -void AddSC_boss_doomlordkazzak(); -void AddSC_boss_doomwalker(); -void AddSC_hellfire_peninsula(); -void AddSC_nagrand(); -void AddSC_netherstorm(); -void AddSC_shadowmoon_valley(); -void AddSC_shattrath_city(); -void AddSC_terokkar_forest(); -void AddSC_zangarmarsh(); - -// Events -void AddSC_event_childrens_week(); - -// Pets -void AddSC_deathknight_pet_scripts(); -void AddSC_generic_pet_scripts(); -void AddSC_hunter_pet_scripts(); -void AddSC_mage_pet_scripts(); -void AddSC_priest_pet_scripts(); -void AddSC_shaman_pet_scripts(); - -// battlegrounds - -// outdoor pvp -void AddSC_outdoorpvp_ep(); -void AddSC_outdoorpvp_hp(); -void AddSC_outdoorpvp_na(); -void AddSC_outdoorpvp_si(); -void AddSC_outdoorpvp_tf(); -void AddSC_outdoorpvp_zm(); - -// player -void AddSC_chat_log(); -void AddSC_action_ip_logger(); - -#endif - -void AddScripts() -{ - AddSpellScripts(); - AddSC_SmartScripts(); - AddCommandScripts(); -#ifdef SCRIPTS - AddWorldScripts(); - AddEasternKingdomsScripts(); - AddKalimdorScripts(); - AddOutlandScripts(); - AddNorthrendScripts(); - AddEventScripts(); - AddPetScripts(); - AddBattlegroundScripts(); - AddOutdoorPvPScripts(); - AddCustomScripts(); -#endif -} - -void AddSpellScripts() -{ - AddSC_deathknight_spell_scripts(); - AddSC_druid_spell_scripts(); - AddSC_generic_spell_scripts(); - AddSC_hunter_spell_scripts(); - AddSC_mage_spell_scripts(); - AddSC_paladin_spell_scripts(); - AddSC_priest_spell_scripts(); - AddSC_rogue_spell_scripts(); - AddSC_shaman_spell_scripts(); - AddSC_warlock_spell_scripts(); - AddSC_warrior_spell_scripts(); - AddSC_quest_spell_scripts(); - AddSC_item_spell_scripts(); - AddSC_holiday_spell_scripts(); -} - -void AddCommandScripts() -{ - AddSC_account_commandscript(); - AddSC_achievement_commandscript(); - AddSC_ahbot_commandscript(); - AddSC_arena_commandscript(); - AddSC_ban_commandscript(); - AddSC_bf_commandscript(); - AddSC_cast_commandscript(); - AddSC_character_commandscript(); - AddSC_cheat_commandscript(); - AddSC_debug_commandscript(); - AddSC_deserter_commandscript(); - AddSC_disable_commandscript(); - AddSC_event_commandscript(); - AddSC_gm_commandscript(); - AddSC_go_commandscript(); - AddSC_gobject_commandscript(); - AddSC_group_commandscript(); - AddSC_guild_commandscript(); - AddSC_honor_commandscript(); - AddSC_instance_commandscript(); - AddSC_learn_commandscript(); - AddSC_lookup_commandscript(); - AddSC_lfg_commandscript(); - AddSC_list_commandscript(); - AddSC_message_commandscript(); - AddSC_misc_commandscript(); - AddSC_mmaps_commandscript(); - AddSC_modify_commandscript(); - AddSC_npc_commandscript(); - AddSC_quest_commandscript(); - AddSC_pet_commandscript(); - AddSC_rbac_commandscript(); - AddSC_reload_commandscript(); - AddSC_reset_commandscript(); - AddSC_send_commandscript(); - AddSC_server_commandscript(); - AddSC_tele_commandscript(); - AddSC_ticket_commandscript(); - AddSC_titles_commandscript(); - AddSC_wp_commandscript(); -} - -void AddWorldScripts() -{ -#ifdef SCRIPTS - AddSC_areatrigger_scripts(); - AddSC_emerald_dragons(); - AddSC_generic_creature(); - AddSC_go_scripts(); - AddSC_guards(); - AddSC_item_scripts(); - AddSC_npc_professions(); - AddSC_npc_innkeeper(); - AddSC_npcs_special(); - AddSC_achievement_scripts(); - AddSC_chat_log(); // location: scripts\World\chat_log.cpp - // To avoid duplicate code, we check once /*ONLY*/ if logging is permitted or not. - if (sWorld->getBoolConfig(CONFIG_IP_BASED_ACTION_LOGGING)) - AddSC_action_ip_logger(); // location: scripts\World\action_ip_logger.cpp - AddSC_duel_reset(); -#endif -} - -void AddEasternKingdomsScripts() -{ -#ifdef SCRIPTS - AddSC_alterac_valley(); //Alterac Valley - AddSC_boss_balinda(); - AddSC_boss_drekthar(); - AddSC_boss_galvangar(); - AddSC_boss_vanndar(); - AddSC_blackrock_depths(); //Blackrock Depths - AddSC_boss_ambassador_flamelash(); - AddSC_boss_draganthaurissan(); - AddSC_boss_general_angerforge(); - AddSC_boss_high_interrogator_gerstahn(); - AddSC_boss_magmus(); - AddSC_boss_moira_bronzebeard(); - AddSC_boss_tomb_of_seven(); - AddSC_instance_blackrock_depths(); - AddSC_boss_drakkisath(); //Blackrock Spire - AddSC_boss_halycon(); - AddSC_boss_highlordomokk(); - AddSC_boss_mothersmolderweb(); - AddSC_boss_overlordwyrmthalak(); - AddSC_boss_shadowvosh(); - AddSC_boss_thebeast(); - AddSC_boss_warmastervoone(); - AddSC_boss_quatermasterzigris(); - AddSC_boss_pyroguard_emberseer(); - AddSC_boss_gyth(); - AddSC_boss_rend_blackhand(); - AddSC_boss_gizrul_the_slavener(); - AddSC_boss_urok_doomhowl(); - AddSC_boss_lord_valthalak(); - AddSC_instance_blackrock_spire(); - AddSC_boss_razorgore(); //Blackwing lair - AddSC_boss_vaelastrasz(); - AddSC_boss_broodlord(); - AddSC_boss_firemaw(); - AddSC_boss_ebonroc(); - AddSC_boss_flamegor(); - AddSC_boss_chromaggus(); - AddSC_boss_nefarian(); - AddSC_instance_blackwing_lair(); - AddSC_deadmines(); //Deadmines - AddSC_boss_mr_smite(); - AddSC_instance_deadmines(); - AddSC_gnomeregan(); //Gnomeregan - AddSC_instance_gnomeregan(); - AddSC_boss_attumen(); //Karazhan - AddSC_boss_curator(); - AddSC_boss_maiden_of_virtue(); - AddSC_boss_shade_of_aran(); - AddSC_boss_malchezaar(); - AddSC_boss_terestian_illhoof(); - AddSC_boss_moroes(); - AddSC_bosses_opera(); - AddSC_boss_netherspite(); - AddSC_instance_karazhan(); - AddSC_karazhan(); - AddSC_boss_nightbane(); - AddSC_boss_felblood_kaelthas(); // Magister's Terrace - AddSC_boss_selin_fireheart(); - AddSC_boss_vexallus(); - AddSC_boss_priestess_delrissa(); - AddSC_instance_magisters_terrace(); - AddSC_magisters_terrace(); - AddSC_boss_lucifron(); //Molten core - AddSC_boss_magmadar(); - AddSC_boss_gehennas(); - AddSC_boss_garr(); - AddSC_boss_baron_geddon(); - AddSC_boss_shazzrah(); - AddSC_boss_golemagg(); - AddSC_boss_sulfuron(); - AddSC_boss_majordomo(); - AddSC_boss_ragnaros(); - AddSC_instance_molten_core(); - AddSC_instance_ragefire_chasm(); //Ragefire Chasm - AddSC_the_scarlet_enclave(); //Scarlet Enclave - AddSC_the_scarlet_enclave_c1(); - AddSC_the_scarlet_enclave_c2(); - AddSC_the_scarlet_enclave_c5(); - AddSC_boss_arcanist_doan(); //Scarlet Monastery - AddSC_boss_azshir_the_sleepless(); - AddSC_boss_bloodmage_thalnos(); - AddSC_boss_headless_horseman(); - AddSC_boss_herod(); - AddSC_boss_high_inquisitor_fairbanks(); - AddSC_boss_houndmaster_loksey(); - AddSC_boss_interrogator_vishas(); - AddSC_boss_scorn(); - AddSC_instance_scarlet_monastery(); - AddSC_boss_mograine_and_whitemane(); - AddSC_boss_darkmaster_gandling(); //Scholomance - AddSC_boss_death_knight_darkreaver(); - AddSC_boss_theolenkrastinov(); - AddSC_boss_illuciabarov(); - AddSC_boss_instructormalicia(); - AddSC_boss_jandicebarov(); - AddSC_boss_kormok(); - AddSC_boss_lordalexeibarov(); - AddSC_boss_lorekeeperpolkelt(); - AddSC_boss_rasfrost(); - AddSC_boss_theravenian(); - AddSC_boss_vectus(); - AddSC_boss_kirtonos_the_herald(); - AddSC_instance_scholomance(); - AddSC_shadowfang_keep(); //Shadowfang keep - AddSC_instance_shadowfang_keep(); - AddSC_boss_magistrate_barthilas(); //Stratholme - AddSC_boss_maleki_the_pallid(); - AddSC_boss_nerubenkan(); - AddSC_boss_cannon_master_willey(); - AddSC_boss_baroness_anastari(); - AddSC_boss_ramstein_the_gorger(); - AddSC_boss_timmy_the_cruel(); - AddSC_boss_postmaster_malown(); - AddSC_boss_baron_rivendare(); - AddSC_boss_dathrohan_balnazzar(); - AddSC_boss_order_of_silver_hand(); - AddSC_instance_stratholme(); - AddSC_stratholme(); - AddSC_sunken_temple(); // Sunken Temple - AddSC_instance_sunken_temple(); - AddSC_instance_sunwell_plateau(); //Sunwell Plateau - AddSC_boss_kalecgos(); - AddSC_boss_brutallus(); - AddSC_boss_felmyst(); - AddSC_boss_eredar_twins(); - AddSC_boss_muru(); - AddSC_boss_kiljaeden(); - AddSC_sunwell_plateau(); - AddSC_instance_the_stockade(); //The Stockade - AddSC_boss_archaedas(); //Uldaman - AddSC_boss_ironaya(); - AddSC_uldaman(); - AddSC_instance_uldaman(); - AddSC_boss_akilzon(); //Zul'Aman - AddSC_boss_halazzi(); - AddSC_boss_hex_lord_malacrass(); - AddSC_boss_janalai(); - AddSC_boss_nalorakk(); - AddSC_boss_zuljin(); - AddSC_instance_zulaman(); - AddSC_zulaman(); - AddSC_boss_jeklik(); //Zul'Gurub - AddSC_boss_venoxis(); - AddSC_boss_marli(); - AddSC_boss_mandokir(); - AddSC_boss_gahzranka(); - AddSC_boss_thekal(); - AddSC_boss_arlokk(); - AddSC_boss_jindo(); - AddSC_boss_hakkar(); - AddSC_boss_grilek(); - AddSC_boss_hazzarah(); - AddSC_boss_renataki(); - AddSC_boss_wushoolay(); - AddSC_instance_zulgurub(); - - //AddSC_alterac_mountains(); - AddSC_arathi_highlands(); - AddSC_blasted_lands(); - AddSC_burning_steppes(); - AddSC_duskwood(); - AddSC_eastern_plaguelands(); - AddSC_ghostlands(); - AddSC_hinterlands(); - AddSC_isle_of_queldanas(); - AddSC_loch_modan(); - AddSC_redridge_mountains(); - AddSC_silverpine_forest(); - AddSC_stormwind_city(); - AddSC_stranglethorn_vale(); - AddSC_swamp_of_sorrows(); - AddSC_tirisfal_glades(); - AddSC_undercity(); - AddSC_western_plaguelands(); - AddSC_wetlands(); -#endif -} - -void AddKalimdorScripts() -{ -#ifdef SCRIPTS - AddSC_blackfathom_deeps(); //Blackfathom Depths - AddSC_boss_gelihast(); - AddSC_boss_kelris(); - AddSC_boss_aku_mai(); - AddSC_instance_blackfathom_deeps(); - AddSC_hyjal(); //CoT Battle for Mt. Hyjal - AddSC_boss_archimonde(); - AddSC_instance_mount_hyjal(); - AddSC_hyjal_trash(); - AddSC_boss_rage_winterchill(); - AddSC_boss_anetheron(); - AddSC_boss_kazrogal(); - AddSC_boss_azgalor(); - AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad - AddSC_boss_epoch_hunter(); - AddSC_boss_lieutenant_drake(); - AddSC_instance_old_hillsbrad(); - AddSC_old_hillsbrad(); - AddSC_boss_aeonus(); //CoT The Black Morass - AddSC_boss_chrono_lord_deja(); - AddSC_boss_temporus(); - AddSC_the_black_morass(); - AddSC_instance_the_black_morass(); - AddSC_boss_epoch(); //CoT Culling Of Stratholme - AddSC_boss_infinite_corruptor(); - AddSC_boss_salramm(); - AddSC_boss_mal_ganis(); - AddSC_boss_meathook(); - AddSC_culling_of_stratholme(); - AddSC_instance_culling_of_stratholme(); - AddSC_instance_dire_maul(); //Dire Maul - AddSC_boss_celebras_the_cursed(); //Maraudon - AddSC_boss_landslide(); - AddSC_boss_noxxion(); - AddSC_boss_ptheradras(); - AddSC_instance_maraudon(); - AddSC_boss_onyxia(); //Onyxia's Lair - AddSC_instance_onyxias_lair(); - AddSC_boss_tuten_kash(); //Razorfen Downs - AddSC_boss_mordresh_fire_eye(); - AddSC_boss_glutton(); - AddSC_boss_amnennar_the_coldbringer(); - AddSC_razorfen_downs(); - AddSC_instance_razorfen_downs(); - AddSC_razorfen_kraul(); //Razorfen Kraul - AddSC_instance_razorfen_kraul(); - AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj - AddSC_boss_rajaxx(); - AddSC_boss_moam(); - AddSC_boss_buru(); - AddSC_boss_ayamiss(); - AddSC_boss_ossirian(); - AddSC_instance_ruins_of_ahnqiraj(); - AddSC_boss_cthun(); //Temple of ahn'qiraj - AddSC_boss_viscidus(); - AddSC_boss_fankriss(); - AddSC_boss_huhuran(); - AddSC_bug_trio(); - AddSC_boss_sartura(); - AddSC_boss_skeram(); - AddSC_boss_twinemperors(); - AddSC_boss_ouro(); - AddSC_npc_anubisath_sentinel(); - AddSC_instance_temple_of_ahnqiraj(); - AddSC_wailing_caverns(); //Wailing caverns - AddSC_instance_wailing_caverns(); - AddSC_boss_zum_rah(); //Zul'Farrak - AddSC_zulfarrak(); - AddSC_instance_zulfarrak(); - - AddSC_ashenvale(); - AddSC_azshara(); - AddSC_azuremyst_isle(); - AddSC_bloodmyst_isle(); - AddSC_boss_azuregos(); - AddSC_darkshore(); - AddSC_desolace(); - AddSC_durotar(); - AddSC_dustwallow_marsh(); - AddSC_felwood(); - AddSC_feralas(); - AddSC_moonglade(); - AddSC_orgrimmar(); - AddSC_silithus(); - AddSC_stonetalon_mountains(); - AddSC_tanaris(); - AddSC_the_barrens(); - AddSC_thousand_needles(); - AddSC_thunder_bluff(); - AddSC_ungoro_crater(); - AddSC_winterspring(); -#endif -} - -void AddOutlandScripts() -{ -#ifdef SCRIPTS - // Auchindoun - Auchenai Crypts - AddSC_boss_shirrak_the_dead_watcher(); - AddSC_boss_exarch_maladaar(); - AddSC_instance_auchenai_crypts(); - - // Auchindoun - Mana Tombs - AddSC_boss_pandemonius(); - AddSC_boss_nexusprince_shaffar(); - AddSC_instance_mana_tombs(); - - // Auchindoun - Sekketh Halls - AddSC_boss_darkweaver_syth(); - AddSC_boss_talon_king_ikiss(); - AddSC_boss_anzu(); - AddSC_instance_sethekk_halls(); - - // Auchindoun - Shadow Labyrinth - AddSC_boss_ambassador_hellmaw(); - AddSC_boss_blackheart_the_inciter(); - AddSC_boss_grandmaster_vorpil(); - AddSC_boss_murmur(); - AddSC_instance_shadow_labyrinth(); - - // Black Temple - AddSC_black_temple(); - AddSC_boss_illidan(); - AddSC_boss_shade_of_akama(); - AddSC_boss_supremus(); - AddSC_boss_gurtogg_bloodboil(); - AddSC_boss_mother_shahraz(); - AddSC_boss_reliquary_of_souls(); - AddSC_boss_teron_gorefiend(); - AddSC_boss_najentus(); - AddSC_boss_illidari_council(); - AddSC_instance_black_temple(); - - // Coilfang Reservoir - Serpent Shrine Cavern - AddSC_boss_fathomlord_karathress(); - AddSC_boss_hydross_the_unstable(); - AddSC_boss_lady_vashj(); - AddSC_boss_leotheras_the_blind(); - AddSC_boss_morogrim_tidewalker(); - AddSC_instance_serpentshrine_cavern(); - AddSC_boss_the_lurker_below(); - - // Coilfang Reservoir - The Steam Vault - AddSC_instance_steam_vault(); - AddSC_boss_hydromancer_thespia(); - AddSC_boss_mekgineer_steamrigger(); - AddSC_boss_warlord_kalithresh(); - - // Coilfang Reservoir - The Slave Pens - AddSC_instance_the_slave_pens(); - AddSC_boss_mennu_the_betrayer(); - AddSC_boss_rokmar_the_crackler(); - AddSC_boss_quagmirran(); - - // Coilfang Reservoir - The Underbog - AddSC_instance_the_underbog(); - AddSC_boss_hungarfen(); - AddSC_boss_the_black_stalker(); - - // Gruul's Lair - AddSC_boss_gruul(); - AddSC_boss_high_king_maulgar(); - AddSC_instance_gruuls_lair(); - AddSC_boss_broggok(); //HC Blood Furnace - AddSC_boss_kelidan_the_breaker(); - AddSC_boss_the_maker(); - AddSC_instance_blood_furnace(); - AddSC_boss_magtheridon(); //HC Magtheridon's Lair - AddSC_instance_magtheridons_lair(); - AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls - AddSC_boss_warbringer_omrogg(); - AddSC_boss_warchief_kargath_bladefist(); - AddSC_shattered_halls(); - AddSC_instance_shattered_halls(); - AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts - AddSC_boss_omor_the_unscarred(); - AddSC_boss_vazruden_the_herald(); - AddSC_instance_ramparts(); - AddSC_arcatraz(); //TK Arcatraz - AddSC_boss_zereketh_the_unbound(); - AddSC_boss_dalliah_the_doomsayer(); - AddSC_boss_wrath_scryer_soccothrates(); - AddSC_boss_harbinger_skyriss(); - AddSC_instance_arcatraz(); - AddSC_boss_high_botanist_freywinn(); //TK Botanica - AddSC_boss_laj(); - AddSC_boss_warp_splinter(); - AddSC_boss_thorngrin_the_tender(); - AddSC_boss_commander_sarannis(); - AddSC_instance_the_botanica(); - AddSC_boss_alar(); //TK The Eye - AddSC_boss_kaelthas(); - AddSC_boss_void_reaver(); - AddSC_boss_high_astromancer_solarian(); - AddSC_instance_the_eye(); - AddSC_the_eye(); - AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar - AddSC_boss_gatewatcher_gyrokill(); - AddSC_boss_nethermancer_sepethrea(); - AddSC_boss_pathaleon_the_calculator(); - AddSC_boss_mechano_lord_capacitus(); - AddSC_instance_mechanar(); - - AddSC_blades_edge_mountains(); - AddSC_boss_doomlordkazzak(); - AddSC_boss_doomwalker(); - AddSC_hellfire_peninsula(); - AddSC_nagrand(); - AddSC_netherstorm(); - AddSC_shadowmoon_valley(); - AddSC_shattrath_city(); - AddSC_terokkar_forest(); - AddSC_zangarmarsh(); -#endif -} - -void AddNorthrendScripts() -{ -#ifdef SCRIPTS - AddSC_boss_slad_ran(); //Gundrak - AddSC_boss_moorabi(); - AddSC_boss_drakkari_colossus(); - AddSC_boss_gal_darah(); - AddSC_boss_eck(); - AddSC_instance_gundrak(); - - // Azjol-Nerub - Ahn'kahet - AddSC_boss_elder_nadox(); - AddSC_boss_taldaram(); - AddSC_boss_amanitar(); - AddSC_boss_jedoga_shadowseeker(); - AddSC_boss_volazj(); - AddSC_instance_ahnkahet(); - - // Azjol-Nerub - Azjol-Nerub - AddSC_boss_krik_thir(); - AddSC_boss_hadronox(); - AddSC_boss_anub_arak(); - AddSC_instance_azjol_nerub(); - - // Drak'Tharon Keep - AddSC_boss_trollgore(); - AddSC_boss_novos(); - AddSC_boss_king_dred(); - AddSC_boss_tharon_ja(); - AddSC_instance_drak_tharon_keep(); - - AddSC_boss_argent_challenge(); //Trial of the Champion - AddSC_boss_black_knight(); - AddSC_boss_grand_champions(); - AddSC_instance_trial_of_the_champion(); - AddSC_trial_of_the_champion(); - AddSC_boss_anubarak_trial(); //Trial of the Crusader - AddSC_boss_faction_champions(); - AddSC_boss_jaraxxus(); - AddSC_trial_of_the_crusader(); - AddSC_boss_twin_valkyr(); - AddSC_boss_northrend_beasts(); - AddSC_instance_trial_of_the_crusader(); - AddSC_boss_anubrekhan(); //Naxxramas - AddSC_boss_maexxna(); - AddSC_boss_patchwerk(); - AddSC_boss_grobbulus(); - AddSC_boss_razuvious(); - AddSC_boss_kelthuzad(); - AddSC_boss_loatheb(); - AddSC_boss_noth(); - AddSC_boss_gluth(); - AddSC_boss_sapphiron(); - AddSC_boss_four_horsemen(); - AddSC_boss_faerlina(); - AddSC_boss_heigan(); - AddSC_boss_gothik(); - AddSC_boss_thaddius(); - AddSC_instance_naxxramas(); - AddSC_boss_nexus_commanders(); // The Nexus Nexus - AddSC_boss_magus_telestra(); - AddSC_boss_anomalus(); - AddSC_boss_ormorok(); - AddSC_boss_keristrasza(); - AddSC_instance_nexus(); - AddSC_boss_drakos(); //The Nexus The Oculus - AddSC_boss_urom(); - AddSC_boss_varos(); - AddSC_boss_eregos(); - AddSC_instance_oculus(); - AddSC_oculus(); - AddSC_boss_malygos(); // The Nexus: Eye of Eternity - AddSC_instance_eye_of_eternity(); - AddSC_boss_sartharion(); //Obsidian Sanctum - AddSC_obsidian_sanctum(); - AddSC_instance_obsidian_sanctum(); - AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning - AddSC_boss_loken(); - AddSC_boss_ionar(); - AddSC_boss_volkhan(); - AddSC_instance_halls_of_lightning(); - AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone - AddSC_boss_krystallus(); - AddSC_boss_sjonnir(); - AddSC_instance_halls_of_stone(); - AddSC_halls_of_stone(); - AddSC_boss_auriaya(); //Ulduar Ulduar - AddSC_boss_flame_leviathan(); - AddSC_boss_ignis(); - AddSC_boss_razorscale(); - AddSC_boss_xt002(); - AddSC_boss_general_vezax(); - AddSC_boss_assembly_of_iron(); - AddSC_boss_kologarn(); - AddSC_boss_mimiron(); - AddSC_boss_hodir(); - AddSC_boss_freya(); - AddSC_boss_yogg_saron(); - AddSC_boss_algalon_the_observer(); - AddSC_instance_ulduar(); - - // Utgarde Keep - Utgarde Keep - AddSC_boss_keleseth(); - AddSC_boss_skarvald_dalronn(); - AddSC_boss_ingvar_the_plunderer(); - AddSC_instance_utgarde_keep(); - AddSC_utgarde_keep(); - - // Utgarde Keep - Utgarde Pinnacle - AddSC_boss_svala(); - AddSC_boss_palehoof(); - AddSC_boss_skadi(); - AddSC_boss_ymiron(); - AddSC_instance_utgarde_pinnacle(); - - // Vault of Archavon - AddSC_boss_archavon(); - AddSC_boss_emalon(); - AddSC_boss_koralon(); - AddSC_boss_toravon(); - AddSC_instance_vault_of_archavon(); - - AddSC_boss_cyanigosa(); //Violet Hold - AddSC_boss_erekem(); - AddSC_boss_ichoron(); - AddSC_boss_lavanthor(); - AddSC_boss_moragg(); - AddSC_boss_xevozz(); - AddSC_boss_zuramat(); - AddSC_instance_violet_hold(); - AddSC_violet_hold(); - AddSC_instance_forge_of_souls(); //Forge of Souls - AddSC_forge_of_souls(); - AddSC_boss_bronjahm(); - AddSC_boss_devourer_of_souls(); - AddSC_instance_pit_of_saron(); //Pit of Saron - AddSC_pit_of_saron(); - AddSC_boss_garfrost(); - AddSC_boss_ick(); - AddSC_boss_tyrannus(); - AddSC_instance_halls_of_reflection(); // Halls of Reflection - AddSC_halls_of_reflection(); - AddSC_boss_falric(); - AddSC_boss_marwyn(); - AddSC_boss_lord_marrowgar(); // Icecrown Citadel - AddSC_boss_lady_deathwhisper(); - AddSC_boss_icecrown_gunship_battle(); - AddSC_boss_deathbringer_saurfang(); - AddSC_boss_festergut(); - AddSC_boss_rotface(); - AddSC_boss_professor_putricide(); - AddSC_boss_blood_prince_council(); - AddSC_boss_blood_queen_lana_thel(); - AddSC_boss_valithria_dreamwalker(); - AddSC_boss_sindragosa(); - AddSC_boss_the_lich_king(); - AddSC_icecrown_citadel_teleport(); - AddSC_instance_icecrown_citadel(); - AddSC_icecrown_citadel(); - AddSC_instance_ruby_sanctum(); // Ruby Sanctum - AddSC_ruby_sanctum(); - AddSC_boss_baltharus_the_warborn(); - AddSC_boss_saviana_ragefire(); - AddSC_boss_general_zarithrian(); - AddSC_boss_halion(); - - AddSC_dalaran(); - AddSC_borean_tundra(); - AddSC_dragonblight(); - AddSC_grizzly_hills(); - AddSC_howling_fjord(); - AddSC_icecrown(); - AddSC_sholazar_basin(); - AddSC_storm_peaks(); - AddSC_wintergrasp(); - AddSC_zuldrak(); - AddSC_crystalsong_forest(); - AddSC_isle_of_conquest(); -#endif -} - -void AddEventScripts() -{ -#ifdef SCRIPTS - AddSC_event_childrens_week(); -#endif -} - -void AddPetScripts() -{ -#ifdef SCRIPTS - AddSC_deathknight_pet_scripts(); - AddSC_generic_pet_scripts(); - AddSC_hunter_pet_scripts(); - AddSC_mage_pet_scripts(); - AddSC_priest_pet_scripts(); - AddSC_shaman_pet_scripts(); -#endif -} - -void AddOutdoorPvPScripts() -{ -#ifdef SCRIPTS - AddSC_outdoorpvp_ep(); - AddSC_outdoorpvp_hp(); - AddSC_outdoorpvp_na(); - AddSC_outdoorpvp_si(); - AddSC_outdoorpvp_tf(); - AddSC_outdoorpvp_zm(); -#endif -} - -void AddBattlegroundScripts() -{ -#ifdef SCRIPTS -#endif -} - -#ifdef SCRIPTS -/* This is where custom scripts' loading functions should be declared. */ - -#endif - -void AddCustomScripts() -{ -#ifdef SCRIPTS - /* This is where custom scripts should be added. */ - -#endif -} diff --git a/src/server/game/Scripting/ScriptMgr.cpp b/src/server/game/Scripting/ScriptMgr.cpp index 37917f64de6..bd3f9cf2bfe 100644 --- a/src/server/game/Scripting/ScriptMgr.cpp +++ b/src/server/game/Scripting/ScriptMgr.cpp @@ -17,15 +17,16 @@ */ #include "ScriptMgr.h" +#include "ScriptReloadMgr.h" #include "Config.h" #include "DatabaseEnv.h" #include "DBCStores.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" -#include "ScriptLoader.h" #include "ScriptSystem.h" #include "Transport.h" #include "Vehicle.h" +#include "SmartAI.h" #include "SpellInfo.h" #include "SpellScript.h" #include "GossipDef.h" @@ -34,12 +35,9 @@ #include "WorldPacket.h" #include "WorldSession.h" #include "Chat.h" - -// namespace -// { - UnusedScriptContainer UnusedScripts; - UnusedScriptNamesContainer UnusedScriptNames; -// } +#include "MapManager.h" +#include "LFGScripts.h" +#include "InstanceScript.h" // Trait which indicates whether this script type // must be assigned in the database. @@ -68,6 +66,10 @@ struct is_script_database_bound<GameObjectScript> : std::true_type { }; template<> +struct is_script_database_bound<VehicleScript> + : std::true_type { }; + +template<> struct is_script_database_bound<AreaTriggerScript> : std::true_type { }; @@ -95,144 +97,850 @@ template<> struct is_script_database_bound<AchievementCriteriaScript> : std::true_type { }; +enum Spells +{ + SPELL_HOTSWAP_VISUAL_SPELL_EFFECT = 40162 // 59084 +}; + +class ScriptRegistryInterface +{ +public: + ScriptRegistryInterface() { } + virtual ~ScriptRegistryInterface() { } + + ScriptRegistryInterface(ScriptRegistryInterface const&) = delete; + ScriptRegistryInterface(ScriptRegistryInterface&&) = delete; + + ScriptRegistryInterface& operator= (ScriptRegistryInterface const&) = delete; + ScriptRegistryInterface& operator= (ScriptRegistryInterface&&) = delete; + + /// Removes all scripts associated with the given script context. + /// Requires ScriptRegistryBase::SwapContext to be called after all transfers have finished. + virtual void ReleaseContext(std::string const& context) = 0; + + /// Injects and updates the changed script objects. + virtual void SwapContext(bool initialize) = 0; + + /// Removes the scripts used by this registry from the given container. + /// Used to find unused script names. + virtual void RemoveUsedScriptsFromContainer(std::unordered_set<std::string>& scripts) = 0; + + /// Unloads the script registry. + virtual void Unload() = 0; +}; + +template<class> +class ScriptRegistry; + +class ScriptRegistryCompositum + : public ScriptRegistryInterface +{ + ScriptRegistryCompositum() { } + + template<class> + friend class ScriptRegistry; + + /// Type erasure wrapper for objects + class DeleteableObjectBase + { + public: + DeleteableObjectBase() { } + virtual ~DeleteableObjectBase() { } + + DeleteableObjectBase(DeleteableObjectBase const&) = delete; + DeleteableObjectBase& operator= (DeleteableObjectBase const&) = delete; + }; + + template<typename T> + class DeleteableObject + : public DeleteableObjectBase + { + public: + DeleteableObject(T&& object) + : _object(std::forward<T>(object)) { } + + private: + T _object; + }; + +public: + void SetScriptNameInContext(std::string const& scriptname, std::string const& context) + { + ASSERT(_scriptnames_to_context.find(scriptname) == _scriptnames_to_context.end(), + "Scriptname was assigned to this context already!"); + _scriptnames_to_context.insert(std::make_pair(scriptname, context)); + } + + std::string const& GetScriptContextOfScriptName(std::string const& scriptname) const + { + auto itr = _scriptnames_to_context.find(scriptname); + ASSERT(itr != _scriptnames_to_context.end() && + "Given scriptname doesn't exist!"); + return itr->second; + } + + void ReleaseContext(std::string const& context) final override + { + for (auto const registry : _registries) + registry->ReleaseContext(context); + + // Clear the script names in context after calling the release hooks + // since it's possible that new references to a shared library + // are acquired when releasing. + for (auto itr = _scriptnames_to_context.begin(); + itr != _scriptnames_to_context.end();) + if (itr->second == context) + itr = _scriptnames_to_context.erase(itr); + else + ++itr; + } + + void SwapContext(bool initialize) final override + { + for (auto const registry : _registries) + registry->SwapContext(initialize); + + DoDelayedDelete(); + } + + void RemoveUsedScriptsFromContainer(std::unordered_set<std::string>& scripts) final override + { + for (auto const registry : _registries) + registry->RemoveUsedScriptsFromContainer(scripts); + } + + void Unload() final override + { + for (auto const registry : _registries) + registry->Unload(); + } + + template<typename T> + void QueueForDelayedDelete(T&& any) + { + _delayed_delete_queue.push_back( + Trinity::make_unique< + DeleteableObject<typename std::decay<T>::type> + >(std::forward<T>(any)) + ); + } + + static ScriptRegistryCompositum* Instance() + { + static ScriptRegistryCompositum instance; + return &instance; + } + +private: + void Register(ScriptRegistryInterface* registry) + { + _registries.insert(registry); + } + + void DoDelayedDelete() + { + _delayed_delete_queue.clear(); + } + + std::unordered_set<ScriptRegistryInterface*> _registries; + + std::vector<std::unique_ptr<DeleteableObjectBase>> _delayed_delete_queue; + + std::unordered_map< + std::string /*script name*/, + std::string /*context*/ + > _scriptnames_to_context; +}; + +#define sScriptRegistryCompositum ScriptRegistryCompositum::Instance() + +template<typename /*ScriptType*/, bool /*IsDatabaseBound*/> +class SpecializedScriptRegistry; + // This is the global static registry of scripts. -template<class TScript> -class ScriptRegistry +template<class ScriptType> +class ScriptRegistry final + : public SpecializedScriptRegistry< + ScriptType, is_script_database_bound<ScriptType>::value> { + ScriptRegistry() + { + sScriptRegistryCompositum->Register(this); + } + +public: + static ScriptRegistry* Instance() + { + static ScriptRegistry instance; + return &instance; + } + + void LogDuplicatedScriptPointerError(ScriptType const* first, ScriptType const* second) + { + // See if the script is using the same memory as another script. If this happens, it means that + // someone forgot to allocate new memory for a script. + TC_LOG_ERROR("scripts", "Script '%s' has same memory pointer as '%s'.", + first->GetName().c_str(), second->GetName().c_str()); + } +}; + +class ScriptRegistrySwapHookBase +{ +public: + ScriptRegistrySwapHookBase() { } + virtual ~ScriptRegistrySwapHookBase() { } + + ScriptRegistrySwapHookBase(ScriptRegistrySwapHookBase const&) = delete; + ScriptRegistrySwapHookBase(ScriptRegistrySwapHookBase&&) = delete; + + ScriptRegistrySwapHookBase& operator= (ScriptRegistrySwapHookBase const&) = delete; + ScriptRegistrySwapHookBase& operator= (ScriptRegistrySwapHookBase&&) = delete; + + /// Called before the actual context release happens + virtual void BeforeReleaseContext(std::string const& /*context*/) { } + + /// Called before SwapContext + virtual void BeforeSwapContext(bool /*initialize*/) { } + + /// Called before Unload + virtual void BeforeUnload() { } +}; + +template<typename ScriptType, typename Base> +class ScriptRegistrySwapHooks + : public ScriptRegistrySwapHookBase +{ +}; + +/// This hook is responsible for swapping OutdoorPvP's +template<typename Base> +class UnsupportedScriptRegistrySwapHooks + : public ScriptRegistrySwapHookBase +{ +public: + void BeforeReleaseContext(std::string const& context) final override + { + auto const bounds = static_cast<Base*>(this)->_ids_of_contexts.equal_range(context); + ASSERT(bounds.first == bounds.second); + } +}; + +/// This hook is responsible for swapping Creature and GameObject AI's +template<typename ObjectType, typename ScriptType, typename Base> +class CreatureGameObjectScriptRegistrySwapHooks + : public ScriptRegistrySwapHookBase +{ + template<typename W> + class AIFunctionMapWorker + { + public: + template<typename T> + AIFunctionMapWorker(T&& worker) + : _worker(std::forward<T>(worker)) { } + + void Visit(std::unordered_map<ObjectGuid, ObjectType*>& objects) + { + _worker(objects); + } + + template<typename O> + void Visit(std::unordered_map<ObjectGuid, O*>&) { } + + private: + W _worker; + }; + + class AsyncCastHotswapEffectEvent : public BasicEvent + { public: + explicit AsyncCastHotswapEffectEvent(Unit* owner) : owner_(owner) { } + + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override + { + owner_->CastSpell(owner_, SPELL_HOTSWAP_VISUAL_SPELL_EFFECT, true); + return true; + } + + private: + Unit* owner_; + }; + + // Hook which is called before a creature is swapped + static void UnloadStage1(Creature* creature) + { + // Remove deletable events only, + // otherwise it causes crashes with non-deletable spell events. + creature->m_Events.KillAllEvents(false); + + if (creature->IsCharmed()) + creature->RemoveCharmedBy(nullptr); + + ASSERT(!creature->IsCharmed(), + "There is a disabled AI which is still loaded."); + + creature->AI()->EnterEvadeMode(); + } + + static void UnloadStage2(Creature* creature) + { + bool const destroyed = creature->AIM_Destroy(); + ASSERT(destroyed, + "Destroying the AI should never fail here!"); + (void)destroyed; + + ASSERT(!creature->AI(), + "The AI should be null here!"); + } + + // Hook which is called before a gameobject is swapped + static void UnloadStage1(GameObject* gameobject) + { + gameobject->AI()->Reset(); + } + + static void UnloadStage2(GameObject* gameobject) + { + gameobject->AIM_Destroy(); + + ASSERT(!gameobject->AI(), + "The AI should be null here!"); + } + + // Hook which is called after a creature was swapped + static void LoadStage1(Creature* creature) + { + ASSERT(!creature->AI(), + "The AI should be null here!"); + + if (creature->IsAlive()) + creature->ClearUnitState(UNIT_STATE_EVADE); + + bool const created = creature->AIM_Initialize(); + ASSERT(created, + "Creating the AI should never fail here!"); + (void)created; + } + + static void LoadStage2(Creature* creature) + { + if (!creature->IsAlive()) + return; + + creature->AI()->EnterEvadeMode(); + + // Cast a dummy visual spell asynchronously here to signal + // that the AI was hot swapped + creature->m_Events.AddEvent(new AsyncCastHotswapEffectEvent(creature), + creature->m_Events.CalculateTime(0)); + } + + // Hook which is called after a gameobject was swapped + static void LoadStage1(GameObject* gameobject) + { + ASSERT(!gameobject->AI(), + "The AI should be null here!"); + + gameobject->AIM_Initialize(); + } + + static void LoadStage2(GameObject* gameobject) + { + gameobject->AI()->Reset(); + } + + template<typename T> + void RunOverAllEntities(T fn) + { + auto evaluator = [&](std::unordered_map<ObjectGuid, ObjectType*>& objects) + { + for (auto object : objects) + fn(object.second); + }; + + AIFunctionMapWorker<typename std::decay<decltype(evaluator)>::type> worker(std::move(evaluator)); + TypeContainerVisitor<decltype(worker), MapStoredObjectTypesContainer> visitor(worker); - typedef std::map<uint32, TScript*> ScriptMap; - typedef typename ScriptMap::iterator ScriptMapIterator; + sMapMgr->DoForAllMaps([&](Map* map) + { + // Run the worker over all maps + visitor.Visit(map->GetObjectsStore()); + }); + } + +public: + void BeforeReleaseContext(std::string const& context) final override + { + auto ids_to_remove = static_cast<Base*>(this)->GetScriptIDsToRemove(context); - // The actual list of scripts. This will be accessed concurrently, so it must not be modified - // after server startup. - static ScriptMap ScriptPointerList; + std::vector<ObjectType*> stage2; - static void AddScript(TScript* const script) + RunOverAllEntities([&](ObjectType* object) { - ASSERT(script); + if (ids_to_remove.find(object->GetScriptId()) != ids_to_remove.end()) + { + UnloadStage1(object); + stage2.push_back(object); + } + }); + + for (auto object : stage2) + UnloadStage2(object); + + // Add the new ids which are removed to the global ids to remove set + ids_removed_.insert(ids_to_remove.begin(), ids_to_remove.end()); + } + + void BeforeSwapContext(bool initialize) override + { + // Never swap creature or gameobject scripts when initializing + if (initialize) + return; + + // Add the recently added scripts to the deleted scripts to replace + // default AI's with recently added core scripts. + ids_removed_.insert(static_cast<Base*>(this)->GetRecentlyAddedScriptIDs().begin(), + static_cast<Base*>(this)->GetRecentlyAddedScriptIDs().end()); + + std::vector<ObjectType*> remove; + std::vector<ObjectType*> stage2; - // See if the script is using the same memory as another script. If this happens, it means that - // someone forgot to allocate new memory for a script. - for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) + RunOverAllEntities([&](ObjectType* object) + { + if (ids_removed_.find(object->GetScriptId()) != ids_removed_.end()) { - if (it->second == script) + if (object->AI()) { - TC_LOG_ERROR("scripts", "Script '%s' has same memory pointer as '%s'.", - script->GetName().c_str(), it->second->GetName().c_str()); - - return; + // Overwrite existing (default) AI's which are replaced by a new script + UnloadStage1(object); + remove.push_back(object); } + + stage2.push_back(object); } + }); + + for (auto object : remove) + UnloadStage2(object); + + for (auto object : stage2) + LoadStage1(object); + + for (auto object : stage2) + LoadStage2(object); + + ids_removed_.clear(); + } + + void BeforeUnload() final override + { + ASSERT(ids_removed_.empty()); + } - AddScript(is_script_database_bound<TScript>{}, script); +private: + std::unordered_set<uint32> ids_removed_; +}; + +// This hook is responsible for swapping CreatureAI's +template<typename Base> +class ScriptRegistrySwapHooks<CreatureScript, Base> + : public CreatureGameObjectScriptRegistrySwapHooks< + Creature, CreatureScript, Base + > { }; + +// This hook is responsible for swapping GameObjectAI's +template<typename Base> +class ScriptRegistrySwapHooks<GameObjectScript, Base> + : public CreatureGameObjectScriptRegistrySwapHooks< + GameObject, GameObjectScript, Base + > { }; + +/// This hook is responsible for swapping BattlegroundScript's +template<typename Base> +class ScriptRegistrySwapHooks<BattlegroundScript, Base> + : public UnsupportedScriptRegistrySwapHooks<Base> { }; + +/// This hook is responsible for swapping OutdoorPvP's +template<typename Base> +class ScriptRegistrySwapHooks<OutdoorPvPScript, Base> + : public ScriptRegistrySwapHookBase +{ +public: + ScriptRegistrySwapHooks() : swapped(false) { } + + void BeforeReleaseContext(std::string const& context) final override + { + auto const bounds = static_cast<Base*>(this)->_ids_of_contexts.equal_range(context); + + if ((!swapped) && (bounds.first != bounds.second)) + { + swapped = true; + sOutdoorPvPMgr->Die(); } + } - // Gets a script by its ID (assigned by ObjectMgr). - static TScript* GetScriptById(uint32 id) + void BeforeSwapContext(bool initialize) override + { + // Never swap outdoor pvp scripts when initializing + if ((!initialize) && swapped) { - ScriptMapIterator it = ScriptPointerList.find(id); - if (it != ScriptPointerList.end()) - return it->second; + sOutdoorPvPMgr->InitOutdoorPvP(); + swapped = false; + } + } + + void BeforeUnload() final override + { + ASSERT(!swapped); + } - return NULL; +private: + bool swapped; +}; + +/// This hook is responsible for swapping InstanceMapScript's +template<typename Base> +class ScriptRegistrySwapHooks<InstanceMapScript, Base> + : public ScriptRegistrySwapHookBase +{ +public: + ScriptRegistrySwapHooks() : swapped(false) { } + + void BeforeReleaseContext(std::string const& context) final override + { + auto const bounds = static_cast<Base*>(this)->_ids_of_contexts.equal_range(context); + if (bounds.first != bounds.second) + swapped = true; + } + + void BeforeSwapContext(bool /*initialize*/) override + { + swapped = false; + } + + void BeforeUnload() final override + { + ASSERT(!swapped); + } + +private: + bool swapped; +}; + +/// This hook is responsible for swapping SpellScriptLoader's +template<typename Base> +class ScriptRegistrySwapHooks<SpellScriptLoader, Base> + : public ScriptRegistrySwapHookBase +{ +public: + ScriptRegistrySwapHooks() : swapped(false) { } + + void BeforeReleaseContext(std::string const& context) final override + { + auto const bounds = static_cast<Base*>(this)->_ids_of_contexts.equal_range(context); + + if (bounds.first != bounds.second) + swapped = true; + } + + void BeforeSwapContext(bool /*initialize*/) override + { + if (swapped) + { + sObjectMgr->ValidateSpellScripts(); + swapped = false; } + } - private: + void BeforeUnload() final override + { + ASSERT(!swapped); + } + +private: + bool swapped; +}; + +// Database bound script registry +template<typename ScriptType> +class SpecializedScriptRegistry<ScriptType, true> + : public ScriptRegistryInterface, + public ScriptRegistrySwapHooks<ScriptType, ScriptRegistry<ScriptType>> +{ + template<typename> + friend class UnsupportedScriptRegistrySwapHooks; - // Adds a database bound script - static void AddScript(std::true_type, TScript* const script) + template<typename, typename> + friend class ScriptRegistrySwapHooks; + + template<typename, typename, typename> + friend class CreatureGameObjectScriptRegistrySwapHooks; + +public: + SpecializedScriptRegistry() { } + + typedef std::unordered_map< + uint32 /*script id*/, + std::unique_ptr<ScriptType> + > ScriptStoreType; + + typedef typename ScriptStoreType::iterator ScriptStoreIteratorType; + + void ReleaseContext(std::string const& context) final override + { + this->BeforeReleaseContext(context); + + auto const bounds = _ids_of_contexts.equal_range(context); + for (auto itr = bounds.first; itr != bounds.second; ++itr) + _scripts.erase(itr->second); + } + + void SwapContext(bool initialize) final override + { + this->BeforeSwapContext(initialize); + + _recently_added_ids.clear(); + } + + void RemoveUsedScriptsFromContainer(std::unordered_set<std::string>& scripts) final override + { + for (auto const& script : _scripts) + scripts.erase(script.second->GetName()); + } + + void Unload() final override + { + this->BeforeUnload(); + + ASSERT(_recently_added_ids.empty(), + "Recently added script ids should be empty here!"); + + _scripts.clear(); + _ids_of_contexts.clear(); + } + + // Adds a database bound script + void AddScript(ScriptType* script) + { + ASSERT(script, + "Tried to call AddScript with a nullpointer!"); + ASSERT(!sScriptMgr->GetCurrentScriptContext().empty(), + "Tried to register a script without being in a valid script context!"); + + std::unique_ptr<ScriptType> script_ptr(script); + + // Get an ID for the script. An ID only exists if it's a script that is assigned in the database + // through a script name (or similar). + if (uint32 const id = sObjectMgr->GetScriptId(script->GetName())) { - // Get an ID for the script. An ID only exists if it's a script that is assigned in the database - // through a script name (or similar). - uint32 id = sObjectMgr->GetScriptId(script->GetName()); - if (id) + // Try to find an existing script. + for (auto const& stored_script : _scripts) { - // Try to find an existing script. - bool existing = false; - for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) - { - // If the script names match... - if (it->second->GetName() == script->GetName()) - { - // ... It exists. - existing = true; - break; - } - } - - // If the script isn't assigned -> assign it! - if (!existing) - { - ScriptPointerList[id] = script; - sScriptMgr->IncrementScriptCount(); - - #ifdef SCRIPTS - UnusedScriptNamesContainer::iterator itr = std::lower_bound(UnusedScriptNames.begin(), UnusedScriptNames.end(), script->GetName()); - if (itr != UnusedScriptNames.end() && *itr == script->GetName()) - UnusedScriptNames.erase(itr); - #endif - } - else + // If the script names match... + if (stored_script.second->GetName() == script->GetName()) { // If the script is already assigned -> delete it! - TC_LOG_ERROR("scripts", "Script '%s' already assigned with the same script name, so the script can't work.", - script->GetName().c_str()); + TC_LOG_ERROR("scripts", "Script '%s' already assigned with the same script name, " + "so the script can't work.", script->GetName().c_str()); - ABORT(); // Error that should be fixed ASAP. + // Error that should be fixed ASAP. + sScriptRegistryCompositum->QueueForDelayedDelete(std::move(script_ptr)); + ABORT(); + return; } } - else + + // If the script isn't assigned -> assign it! + _scripts.insert(std::make_pair(id, std::move(script_ptr))); + _ids_of_contexts.insert(std::make_pair(sScriptMgr->GetCurrentScriptContext(), id)); + _recently_added_ids.insert(id); + + sScriptRegistryCompositum->SetScriptNameInContext(script->GetName(), + sScriptMgr->GetCurrentScriptContext()); + } + else + { + // The script uses a script name from database, but isn't assigned to anything. + TC_LOG_ERROR("sql.sql", "Script named '%s' does not have a script name assigned in database.", + script->GetName().c_str()); + + // Avoid calling "delete script;" because we are currently in the script constructor + // In a valid scenario this will not happen because every script has a name assigned in the database + sScriptRegistryCompositum->QueueForDelayedDelete(std::move(script_ptr)); + return; + } + } + + // Gets a script by its ID (assigned by ObjectMgr). + ScriptType* GetScriptById(uint32 id) + { + auto const itr = _scripts.find(id); + if (itr != _scripts.end()) + return itr->second.get(); + + return nullptr; + } + + ScriptStoreType& GetScripts() + { + return _scripts; + } + +protected: + // Returns the script id's which are registered to a certain context + std::unordered_set<uint32> GetScriptIDsToRemove(std::string const& context) const + { + // Create a set of all ids which are removed + std::unordered_set<uint32> scripts_to_remove; + + auto const bounds = _ids_of_contexts.equal_range(context); + for (auto itr = bounds.first; itr != bounds.second; ++itr) + scripts_to_remove.insert(itr->second); + + return scripts_to_remove; + } + + std::unordered_set<uint32> const& GetRecentlyAddedScriptIDs() const + { + return _recently_added_ids; + } + +private: + ScriptStoreType _scripts; + + // Scripts of a specific context + std::unordered_multimap<std::string /*context*/, uint32 /*id*/> _ids_of_contexts; + + // Script id's which were registered recently + std::unordered_set<uint32> _recently_added_ids; +}; + +/// This hook is responsible for swapping CommandScript's +template<typename Base> +class ScriptRegistrySwapHooks<CommandScript, Base> + : public ScriptRegistrySwapHookBase +{ +public: + void BeforeReleaseContext(std::string const& /*context*/) final override + { + ChatHandler::invalidateCommandTable(); + } + + void BeforeSwapContext(bool /*initialize*/) override + { + ChatHandler::invalidateCommandTable(); + } + + void BeforeUnload() final override + { + ChatHandler::invalidateCommandTable(); + } +}; + +// Database unbound script registry +template<typename ScriptType> +class SpecializedScriptRegistry<ScriptType, false> + : public ScriptRegistryInterface, + public ScriptRegistrySwapHooks<ScriptType, ScriptRegistry<ScriptType>> +{ + template<typename, typename> + friend class ScriptRegistrySwapHooks; + +public: + typedef std::unordered_multimap<std::string /*context*/, std::unique_ptr<ScriptType>> ScriptStoreType; + typedef typename ScriptStoreType::iterator ScriptStoreIteratorType; + + SpecializedScriptRegistry() { } + + void ReleaseContext(std::string const& context) final override + { + this->BeforeReleaseContext(context); + + _scripts.erase(context); + } + + void SwapContext(bool initialize) final override + { + this->BeforeSwapContext(initialize); + } + + void RemoveUsedScriptsFromContainer(std::unordered_set<std::string>& scripts) final override + { + for (auto const& script : _scripts) + scripts.erase(script.second->GetName()); + } + + void Unload() final override + { + this->BeforeUnload(); + + _scripts.clear(); + } + + // Adds a non database bound script + void AddScript(ScriptType* script) + { + ASSERT(script, + "Tried to call AddScript with a nullpointer!"); + ASSERT(!sScriptMgr->GetCurrentScriptContext().empty(), + "Tried to register a script without being in a valid script context!"); + + std::unique_ptr<ScriptType> script_ptr(script); + + for (auto const& entry : _scripts) + if (entry.second.get() == script) { - // The script uses a script name from database, but isn't assigned to anything. - TC_LOG_ERROR("sql.sql", "Script named '%s' does not have a script name assigned in database.", script->GetName().c_str()); + static_cast<ScriptRegistry<ScriptType>*>(this)-> + LogDuplicatedScriptPointerError(script, entry.second.get()); - // Avoid calling "delete script;" because we are currently in the script constructor - // In a valid scenario this will not happen because every script has a name assigned in the database - UnusedScripts.push_back(script); + sScriptRegistryCompositum->QueueForDelayedDelete(std::move(script_ptr)); return; } - } - // Adds a non database bound script - static void AddScript(std::false_type, TScript* const script) - { - // We're dealing with a code-only script; just add it. - ScriptPointerList[_scriptIdCounter++] = script; - sScriptMgr->IncrementScriptCount(); - } + // We're dealing with a code-only script, just add it. + _scripts.insert(std::make_pair(sScriptMgr->GetCurrentScriptContext(), std::move(script_ptr))); + } + + ScriptStoreType& GetScripts() + { + return _scripts; + } - // Counter used for code-only scripts. - static uint32 _scriptIdCounter; +private: + ScriptStoreType _scripts; }; // Utility macros to refer to the script registry. -#define SCR_REG_MAP(T) ScriptRegistry<T>::ScriptMap -#define SCR_REG_ITR(T) ScriptRegistry<T>::ScriptMapIterator -#define SCR_REG_LST(T) ScriptRegistry<T>::ScriptPointerList +#define SCR_REG_MAP(T) ScriptRegistry<T>::ScriptStoreType +#define SCR_REG_ITR(T) ScriptRegistry<T>::ScriptStoreIteratorType +#define SCR_REG_LST(T) ScriptRegistry<T>::Instance()->GetScripts() // Utility macros for looping over scripts. #define FOR_SCRIPTS(T, C, E) \ if (SCR_REG_LST(T).empty()) \ return; \ + \ for (SCR_REG_ITR(T) C = SCR_REG_LST(T).begin(); \ C != SCR_REG_LST(T).end(); ++C) + #define FOR_SCRIPTS_RET(T, C, E, R) \ if (SCR_REG_LST(T).empty()) \ return R; \ + \ for (SCR_REG_ITR(T) C = SCR_REG_LST(T).begin(); \ C != SCR_REG_LST(T).end(); ++C) + #define FOREACH_SCRIPT(T) \ FOR_SCRIPTS(T, itr, end) \ - itr->second + itr->second // Utility macros for finding specific scripts. #define GET_SCRIPT(T, I, V) \ - T* V = ScriptRegistry<T>::GetScriptById(I); \ + T* V = ScriptRegistry<T>::Instance()->GetScriptById(I); \ if (!V) \ return; + #define GET_SCRIPT_RET(T, I, V, R) \ - T* V = ScriptRegistry<T>::GetScriptById(I); \ + T* V = ScriptRegistry<T>::Instance()->GetScriptById(I); \ if (!V) \ return R; @@ -242,14 +950,34 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } *SpellSummary; -ScriptMgr::ScriptMgr() : _scriptCount(0), _scheduledScripts(0) +ScriptObject::ScriptObject(const char* name) : _name(name) +{ + sScriptMgr->IncreaseScriptCount(); +} + +ScriptObject::~ScriptObject() +{ + sScriptMgr->DecreaseScriptCount(); +} + +ScriptMgr::ScriptMgr() + : _scriptCount(0), _script_loader_callback(nullptr) { } ScriptMgr::~ScriptMgr() { } +ScriptMgr* ScriptMgr::instance() +{ + static ScriptMgr instance; + return &instance; +} + void ScriptMgr::Initialize() { + ASSERT(sSpellMgr->GetSpellInfo(SPELL_HOTSWAP_VISUAL_SPELL_EFFECT) + && "Reload hotswap spell effect for creatures isn't valid!"); + uint32 oldMSTime = getMSTime(); LoadDatabase(); @@ -257,68 +985,95 @@ void ScriptMgr::Initialize() TC_LOG_INFO("server.loading", "Loading C++ scripts"); FillSpellSummary(); - AddScripts(); -#ifdef SCRIPTS - for (std::string const& scriptName : UnusedScriptNames) + // Load core scripts + SetScriptContext(GetNameOfStaticContext()); + + // SmartAI + AddSC_SmartScripts(); + + // LFGScripts + lfg::AddSC_LFGScripts(); + + // Load all static linked scripts through the script loader function. + ASSERT(_script_loader_callback, + "Script loader callback wasn't registered!"); + _script_loader_callback(); + + // Initialize all dynamic scripts + // and finishes the context switch to do + // bulk loading + sScriptReloadMgr->Initialize(); + + // Loads all scripts from the current context + sScriptMgr->SwapScriptContext(true); + + // Print unused script names. + std::unordered_set<std::string> unusedScriptNames( + sObjectMgr->GetAllScriptNames().begin(), + sObjectMgr->GetAllScriptNames().end()); + + // Remove the used scripts from the given container. + sScriptRegistryCompositum->RemoveUsedScriptsFromContainer(unusedScriptNames); + + for (std::string const& scriptName : unusedScriptNames) { - TC_LOG_ERROR("sql.sql", "ScriptName '%s' exists in database, but no core script found!", scriptName.c_str()); + // Avoid complaining about empty script names since the + // script name container contains a placeholder as the 0 element. + if (scriptName.empty()) + continue; + + TC_LOG_ERROR("sql.sql", "ScriptName '%s' exists in database, " + "but no core script found!", scriptName.c_str()); } -#endif - UnloadUnusedScripts(); + TC_LOG_INFO("server.loading", ">> Loaded %u C++ scripts in %u ms", + GetScriptCount(), GetMSTimeDiffToNow(oldMSTime)); +} - TC_LOG_INFO("server.loading", ">> Loaded %u C++ scripts in %u ms", GetScriptCount(), GetMSTimeDiffToNow(oldMSTime)); +void ScriptMgr::SetScriptContext(std::string const& context) +{ + _currentContext = context; } -void ScriptMgr::Unload() +void ScriptMgr::SwapScriptContext(bool initialize) { - #define SCR_CLEAR(T) \ - for (SCR_REG_ITR(T) itr = SCR_REG_LST(T).begin(); itr != SCR_REG_LST(T).end(); ++itr) \ - delete itr->second; \ - SCR_REG_LST(T).clear(); - - // Clear scripts for every script type. - SCR_CLEAR(SpellScriptLoader); - SCR_CLEAR(ServerScript); - SCR_CLEAR(WorldScript); - SCR_CLEAR(FormulaScript); - SCR_CLEAR(WorldMapScript); - SCR_CLEAR(InstanceMapScript); - SCR_CLEAR(BattlegroundMapScript); - SCR_CLEAR(ItemScript); - SCR_CLEAR(CreatureScript); - SCR_CLEAR(GameObjectScript); - SCR_CLEAR(AreaTriggerScript); - SCR_CLEAR(BattlegroundScript); - SCR_CLEAR(OutdoorPvPScript); - SCR_CLEAR(CommandScript); - SCR_CLEAR(WeatherScript); - SCR_CLEAR(AuctionHouseScript); - SCR_CLEAR(ConditionScript); - SCR_CLEAR(VehicleScript); - SCR_CLEAR(DynamicObjectScript); - SCR_CLEAR(TransportScript); - SCR_CLEAR(AchievementCriteriaScript); - SCR_CLEAR(PlayerScript); - SCR_CLEAR(AccountScript); - SCR_CLEAR(GuildScript); - SCR_CLEAR(GroupScript); - SCR_CLEAR(UnitScript); - - #undef SCR_CLEAR - - UnloadUnusedScripts(); + sScriptRegistryCompositum->SwapContext(initialize); + _currentContext.clear(); +} - delete[] SpellSummary; - delete[] UnitAI::AISpellInfo; +std::string const& ScriptMgr::GetNameOfStaticContext() +{ + static std::string const name = "___static___"; + return name; } -void ScriptMgr::UnloadUnusedScripts() +void ScriptMgr::ReleaseScriptContext(std::string const& context) { - for (size_t i = 0; i < UnusedScripts.size(); ++i) - delete UnusedScripts[i]; - UnusedScripts.clear(); + sScriptRegistryCompositum->ReleaseContext(context); +} + +std::shared_ptr<ModuleReference> + ScriptMgr::AcquireModuleReferenceOfScriptName(std::string const& scriptname) const +{ +#ifdef TRINITY_API_USE_DYNAMIC_LINKING + // Returns the reference to the module of the given scriptname + return ScriptReloadMgr::AcquireModuleReferenceOfContext( + sScriptRegistryCompositum->GetScriptContextOfScriptName(scriptname)); +#else + (void)scriptname; + // Something went wrong when this function is used in + // a static linked context. + WPAbort(); +#endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING +} + +void ScriptMgr::Unload() +{ + sScriptRegistryCompositum->Unload(); + + delete[] SpellSummary; + delete[] UnitAI::AISpellInfo; } void ScriptMgr::LoadDatabase() @@ -413,38 +1168,22 @@ void ScriptMgr::FillSpellSummary() } } -void ScriptMgr::CreateSpellScripts(uint32 spellId, std::list<SpellScript*>& scriptVector) +template<typename T, typename F> +void CreateSpellOrAuraScripts(uint32 spellId, std::list<T*>& scriptVector, F&& extractor) { SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) { - SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); - if (!tmpscript) - continue; - - SpellScript* script = tmpscript->GetSpellScript(); - - if (!script) + // When the script is disabled continue with the next one + if (!itr->second.second) continue; - script->_Init(&tmpscript->GetName(), spellId); - - scriptVector.push_back(script); - } -} - -void ScriptMgr::CreateAuraScripts(uint32 spellId, std::list<AuraScript*>& scriptVector) -{ - SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); - - for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) - { - SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); + SpellScriptLoader* tmpscript = sScriptMgr->GetSpellScriptLoader(itr->second.first); if (!tmpscript) continue; - AuraScript* script = tmpscript->GetAuraScript(); + T* script = (*tmpscript.*extractor)(); if (!script) continue; @@ -455,19 +1194,19 @@ void ScriptMgr::CreateAuraScripts(uint32 spellId, std::list<AuraScript*>& script } } -void ScriptMgr::CreateSpellScriptLoaders(uint32 spellId, std::vector<std::pair<SpellScriptLoader*, SpellScriptsContainer::iterator> >& scriptVector) +void ScriptMgr::CreateSpellScripts(uint32 spellId, std::list<SpellScript*>& scriptVector) { - SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spellId); - scriptVector.reserve(std::distance(bounds.first, bounds.second)); + CreateSpellOrAuraScripts(spellId, scriptVector, &SpellScriptLoader::GetSpellScript); +} - for (SpellScriptsContainer::iterator itr = bounds.first; itr != bounds.second; ++itr) - { - SpellScriptLoader* tmpscript = ScriptRegistry<SpellScriptLoader>::GetScriptById(itr->second); - if (!tmpscript) - continue; +void ScriptMgr::CreateAuraScripts(uint32 spellId, std::list<AuraScript*>& scriptVector) +{ + CreateSpellOrAuraScripts(spellId, scriptVector, &SpellScriptLoader::GetAuraScript); +} - scriptVector.push_back(std::make_pair(tmpscript, itr)); - } +SpellScriptLoader* ScriptMgr::GetSpellScriptLoader(uint32 scriptId) +{ + return ScriptRegistry<SpellScriptLoader>::Instance()->GetScriptById(scriptId); } void ScriptMgr::OnNetworkStart() @@ -514,17 +1253,6 @@ void ScriptMgr::OnPacketSend(WorldSession* session, WorldPacket const& packet) FOREACH_SCRIPT(ServerScript)->OnPacketSend(session, copy); } -void ScriptMgr::OnUnknownPacketReceive(WorldSession* session, WorldPacket const& packet) -{ - ASSERT(session); - - if (SCR_REG_LST(ServerScript).empty()) - return; - - WorldPacket copy(packet); - FOREACH_SCRIPT(ServerScript)->OnUnknownPacketReceive(session, copy); -} - void ScriptMgr::OnOpenStateChange(bool open) { FOREACH_SCRIPT(WorldScript)->OnOpenStateChange(open); @@ -1506,57 +2234,62 @@ void ScriptMgr::OnGroupDisband(Group* group) void ScriptMgr::OnHeal(Unit* healer, Unit* reciever, uint32& gain) { FOREACH_SCRIPT(UnitScript)->OnHeal(healer, reciever, gain); + FOREACH_SCRIPT(PlayerScript)->OnHeal(healer, reciever, gain); } void ScriptMgr::OnDamage(Unit* attacker, Unit* victim, uint32& damage) { FOREACH_SCRIPT(UnitScript)->OnDamage(attacker, victim, damage); + FOREACH_SCRIPT(PlayerScript)->OnDamage(attacker, victim, damage); } void ScriptMgr::ModifyPeriodicDamageAurasTick(Unit* target, Unit* attacker, uint32& damage) { FOREACH_SCRIPT(UnitScript)->ModifyPeriodicDamageAurasTick(target, attacker, damage); + FOREACH_SCRIPT(PlayerScript)->ModifyPeriodicDamageAurasTick(target, attacker, damage); } void ScriptMgr::ModifyMeleeDamage(Unit* target, Unit* attacker, uint32& damage) { FOREACH_SCRIPT(UnitScript)->ModifyMeleeDamage(target, attacker, damage); + FOREACH_SCRIPT(PlayerScript)->ModifyMeleeDamage(target, attacker, damage); } void ScriptMgr::ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& damage) { FOREACH_SCRIPT(UnitScript)->ModifySpellDamageTaken(target, attacker, damage); + FOREACH_SCRIPT(PlayerScript)->ModifySpellDamageTaken(target, attacker, damage); } SpellScriptLoader::SpellScriptLoader(const char* name) : ScriptObject(name) { - ScriptRegistry<SpellScriptLoader>::AddScript(this); + ScriptRegistry<SpellScriptLoader>::Instance()->AddScript(this); } ServerScript::ServerScript(const char* name) : ScriptObject(name) { - ScriptRegistry<ServerScript>::AddScript(this); + ScriptRegistry<ServerScript>::Instance()->AddScript(this); } WorldScript::WorldScript(const char* name) : ScriptObject(name) { - ScriptRegistry<WorldScript>::AddScript(this); + ScriptRegistry<WorldScript>::Instance()->AddScript(this); } FormulaScript::FormulaScript(const char* name) : ScriptObject(name) { - ScriptRegistry<FormulaScript>::AddScript(this); + ScriptRegistry<FormulaScript>::Instance()->AddScript(this); } UnitScript::UnitScript(const char* name, bool addToScripts) : ScriptObject(name) { if (addToScripts) - ScriptRegistry<UnitScript>::AddScript(this); + ScriptRegistry<UnitScript>::Instance()->AddScript(this); } WorldMapScript::WorldMapScript(const char* name, uint32 mapId) @@ -1565,7 +2298,7 @@ WorldMapScript::WorldMapScript(const char* name, uint32 mapId) if (GetEntry() && !GetEntry()->IsWorldMap()) TC_LOG_ERROR("scripts", "WorldMapScript for map %u is invalid.", mapId); - ScriptRegistry<WorldMapScript>::AddScript(this); + ScriptRegistry<WorldMapScript>::Instance()->AddScript(this); } InstanceMapScript::InstanceMapScript(const char* name, uint32 mapId) @@ -1574,7 +2307,7 @@ InstanceMapScript::InstanceMapScript(const char* name, uint32 mapId) if (GetEntry() && !GetEntry()->IsDungeon()) TC_LOG_ERROR("scripts", "InstanceMapScript for map %u is invalid.", mapId); - ScriptRegistry<InstanceMapScript>::AddScript(this); + ScriptRegistry<InstanceMapScript>::Instance()->AddScript(this); } BattlegroundMapScript::BattlegroundMapScript(const char* name, uint32 mapId) @@ -1583,155 +2316,141 @@ BattlegroundMapScript::BattlegroundMapScript(const char* name, uint32 mapId) if (GetEntry() && !GetEntry()->IsBattleground()) TC_LOG_ERROR("scripts", "BattlegroundMapScript for map %u is invalid.", mapId); - ScriptRegistry<BattlegroundMapScript>::AddScript(this); + ScriptRegistry<BattlegroundMapScript>::Instance()->AddScript(this); } ItemScript::ItemScript(const char* name) : ScriptObject(name) { - ScriptRegistry<ItemScript>::AddScript(this); + ScriptRegistry<ItemScript>::Instance()->AddScript(this); } CreatureScript::CreatureScript(const char* name) : UnitScript(name, false) { - ScriptRegistry<CreatureScript>::AddScript(this); + ScriptRegistry<CreatureScript>::Instance()->AddScript(this); } GameObjectScript::GameObjectScript(const char* name) : ScriptObject(name) { - ScriptRegistry<GameObjectScript>::AddScript(this); + ScriptRegistry<GameObjectScript>::Instance()->AddScript(this); } AreaTriggerScript::AreaTriggerScript(const char* name) : ScriptObject(name) { - ScriptRegistry<AreaTriggerScript>::AddScript(this); + ScriptRegistry<AreaTriggerScript>::Instance()->AddScript(this); } BattlegroundScript::BattlegroundScript(const char* name) : ScriptObject(name) { - ScriptRegistry<BattlegroundScript>::AddScript(this); + ScriptRegistry<BattlegroundScript>::Instance()->AddScript(this); } OutdoorPvPScript::OutdoorPvPScript(const char* name) : ScriptObject(name) { - ScriptRegistry<OutdoorPvPScript>::AddScript(this); + ScriptRegistry<OutdoorPvPScript>::Instance()->AddScript(this); } CommandScript::CommandScript(const char* name) : ScriptObject(name) { - ScriptRegistry<CommandScript>::AddScript(this); + ScriptRegistry<CommandScript>::Instance()->AddScript(this); } WeatherScript::WeatherScript(const char* name) : ScriptObject(name) { - ScriptRegistry<WeatherScript>::AddScript(this); + ScriptRegistry<WeatherScript>::Instance()->AddScript(this); } AuctionHouseScript::AuctionHouseScript(const char* name) : ScriptObject(name) { - ScriptRegistry<AuctionHouseScript>::AddScript(this); + ScriptRegistry<AuctionHouseScript>::Instance()->AddScript(this); } ConditionScript::ConditionScript(const char* name) : ScriptObject(name) { - ScriptRegistry<ConditionScript>::AddScript(this); + ScriptRegistry<ConditionScript>::Instance()->AddScript(this); } VehicleScript::VehicleScript(const char* name) : ScriptObject(name) { - ScriptRegistry<VehicleScript>::AddScript(this); + ScriptRegistry<VehicleScript>::Instance()->AddScript(this); } DynamicObjectScript::DynamicObjectScript(const char* name) : ScriptObject(name) { - ScriptRegistry<DynamicObjectScript>::AddScript(this); + ScriptRegistry<DynamicObjectScript>::Instance()->AddScript(this); } TransportScript::TransportScript(const char* name) : ScriptObject(name) { - ScriptRegistry<TransportScript>::AddScript(this); + ScriptRegistry<TransportScript>::Instance()->AddScript(this); } AchievementCriteriaScript::AchievementCriteriaScript(const char* name) : ScriptObject(name) { - ScriptRegistry<AchievementCriteriaScript>::AddScript(this); + ScriptRegistry<AchievementCriteriaScript>::Instance()->AddScript(this); } PlayerScript::PlayerScript(const char* name) : UnitScript(name, false) { - ScriptRegistry<PlayerScript>::AddScript(this); + ScriptRegistry<PlayerScript>::Instance()->AddScript(this); } AccountScript::AccountScript(const char* name) : ScriptObject(name) { - ScriptRegistry<AccountScript>::AddScript(this); + ScriptRegistry<AccountScript>::Instance()->AddScript(this); } GuildScript::GuildScript(const char* name) : ScriptObject(name) { - ScriptRegistry<GuildScript>::AddScript(this); + ScriptRegistry<GuildScript>::Instance()->AddScript(this); } GroupScript::GroupScript(const char* name) : ScriptObject(name) { - ScriptRegistry<GroupScript>::AddScript(this); + ScriptRegistry<GroupScript>::Instance()->AddScript(this); } -// Instantiate static members of ScriptRegistry. -template<class TScript> std::map<uint32, TScript*> ScriptRegistry<TScript>::ScriptPointerList; -template<class TScript> uint32 ScriptRegistry<TScript>::_scriptIdCounter = 0; - // Specialize for each script type class like so: -template class ScriptRegistry<SpellScriptLoader>; -template class ScriptRegistry<ServerScript>; -template class ScriptRegistry<WorldScript>; -template class ScriptRegistry<FormulaScript>; -template class ScriptRegistry<WorldMapScript>; -template class ScriptRegistry<InstanceMapScript>; -template class ScriptRegistry<BattlegroundMapScript>; -template class ScriptRegistry<ItemScript>; -template class ScriptRegistry<CreatureScript>; -template class ScriptRegistry<GameObjectScript>; -template class ScriptRegistry<AreaTriggerScript>; -template class ScriptRegistry<BattlegroundScript>; -template class ScriptRegistry<OutdoorPvPScript>; -template class ScriptRegistry<CommandScript>; -template class ScriptRegistry<WeatherScript>; -template class ScriptRegistry<AuctionHouseScript>; -template class ScriptRegistry<ConditionScript>; -template class ScriptRegistry<VehicleScript>; -template class ScriptRegistry<DynamicObjectScript>; -template class ScriptRegistry<TransportScript>; -template class ScriptRegistry<AchievementCriteriaScript>; -template class ScriptRegistry<PlayerScript>; -template class ScriptRegistry<GuildScript>; -template class ScriptRegistry<GroupScript>; -template class ScriptRegistry<UnitScript>; -template class ScriptRegistry<AccountScript>; - -// Undefine utility macros. -#undef GET_SCRIPT_RET -#undef GET_SCRIPT -#undef FOREACH_SCRIPT -#undef FOR_SCRIPTS_RET -#undef FOR_SCRIPTS -#undef SCR_REG_LST -#undef SCR_REG_ITR -#undef SCR_REG_MAP +template class TC_GAME_API ScriptRegistry<SpellScriptLoader>; +template class TC_GAME_API ScriptRegistry<ServerScript>; +template class TC_GAME_API ScriptRegistry<WorldScript>; +template class TC_GAME_API ScriptRegistry<FormulaScript>; +template class TC_GAME_API ScriptRegistry<WorldMapScript>; +template class TC_GAME_API ScriptRegistry<InstanceMapScript>; +template class TC_GAME_API ScriptRegistry<BattlegroundMapScript>; +template class TC_GAME_API ScriptRegistry<ItemScript>; +template class TC_GAME_API ScriptRegistry<CreatureScript>; +template class TC_GAME_API ScriptRegistry<GameObjectScript>; +template class TC_GAME_API ScriptRegistry<AreaTriggerScript>; +template class TC_GAME_API ScriptRegistry<BattlegroundScript>; +template class TC_GAME_API ScriptRegistry<OutdoorPvPScript>; +template class TC_GAME_API ScriptRegistry<CommandScript>; +template class TC_GAME_API ScriptRegistry<WeatherScript>; +template class TC_GAME_API ScriptRegistry<AuctionHouseScript>; +template class TC_GAME_API ScriptRegistry<ConditionScript>; +template class TC_GAME_API ScriptRegistry<VehicleScript>; +template class TC_GAME_API ScriptRegistry<DynamicObjectScript>; +template class TC_GAME_API ScriptRegistry<TransportScript>; +template class TC_GAME_API ScriptRegistry<AchievementCriteriaScript>; +template class TC_GAME_API ScriptRegistry<PlayerScript>; +template class TC_GAME_API ScriptRegistry<GuildScript>; +template class TC_GAME_API ScriptRegistry<GroupScript>; +template class TC_GAME_API ScriptRegistry<UnitScript>; +template class TC_GAME_API ScriptRegistry<AccountScript>; diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index 6706c4f9c14..233e56aadb2 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -46,6 +46,7 @@ class InstanceMap; class InstanceScript; class Item; class Map; +class ModuleReference; class OutdoorPvP; class Player; class Quest; @@ -147,7 +148,7 @@ struct OutdoorPvPData; event on all registered scripts of that type. */ -class ScriptObject +class TC_GAME_API ScriptObject { friend class ScriptMgr; @@ -157,14 +158,8 @@ class ScriptObject protected: - ScriptObject(const char* name) - : _name(name) - { - } - - virtual ~ScriptObject() - { - } + ScriptObject(const char* name); + virtual ~ScriptObject(); private: @@ -186,7 +181,7 @@ template<class TObject> class UpdatableScript virtual void OnUpdate(TObject* /*obj*/, uint32 /*diff*/) { } }; -class SpellScriptLoader : public ScriptObject +class TC_GAME_API SpellScriptLoader : public ScriptObject { protected: @@ -201,7 +196,7 @@ class SpellScriptLoader : public ScriptObject virtual AuraScript* GetAuraScript() const { return NULL; } }; -class ServerScript : public ScriptObject +class TC_GAME_API ServerScript : public ScriptObject { protected: @@ -229,13 +224,9 @@ class ServerScript : public ScriptObject // Called when a (valid) packet is received by a client. The packet object is a copy of the original packet, so // reading and modifying it is safe. Make sure to check WorldSession pointer before usage, it might be null in case of auth packets virtual void OnPacketReceive(WorldSession* /*session*/, WorldPacket& /*packet*/) { } - - // Called when an invalid (unknown opcode) packet is received by a client. The packet is a reference to the orignal - // packet; not a copy. This allows you to actually handle unknown packets (for whatever purpose). - virtual void OnUnknownPacketReceive(WorldSession* /*session*/, WorldPacket& /*packet*/) { } }; -class WorldScript : public ScriptObject +class TC_GAME_API WorldScript : public ScriptObject { protected: @@ -268,7 +259,7 @@ class WorldScript : public ScriptObject virtual void OnShutdown() { } }; -class FormulaScript : public ScriptObject +class TC_GAME_API FormulaScript : public ScriptObject { protected: @@ -335,14 +326,15 @@ template<class TMap> class MapScript : public UpdatableScript<TMap> virtual void OnPlayerLeave(TMap* /*map*/, Player* /*player*/) { } }; -class WorldMapScript : public ScriptObject, public MapScript<Map> +class TC_GAME_API WorldMapScript : public ScriptObject, public MapScript<Map> { protected: WorldMapScript(const char* name, uint32 mapId); }; -class InstanceMapScript : public ScriptObject, public MapScript<InstanceMap> +class TC_GAME_API InstanceMapScript + : public ScriptObject, public MapScript<InstanceMap> { protected: @@ -354,14 +346,14 @@ class InstanceMapScript : public ScriptObject, public MapScript<InstanceMap> virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return NULL; } }; -class BattlegroundMapScript : public ScriptObject, public MapScript<BattlegroundMap> +class TC_GAME_API BattlegroundMapScript : public ScriptObject, public MapScript<BattlegroundMap> { protected: BattlegroundMapScript(const char* name, uint32 mapId); }; -class ItemScript : public ScriptObject +class TC_GAME_API ItemScript : public ScriptObject { protected: @@ -385,7 +377,7 @@ class ItemScript : public ScriptObject virtual bool OnRemove(Player* /*player*/, Item* /*item*/) { return false; } }; -class UnitScript : public ScriptObject +class TC_GAME_API UnitScript : public ScriptObject { protected: @@ -408,7 +400,7 @@ class UnitScript : public ScriptObject virtual void ModifySpellDamageTaken(Unit* /*target*/, Unit* /*attacker*/, int32& /*damage*/) { } }; -class CreatureScript : public UnitScript, public UpdatableScript<Creature> +class TC_GAME_API CreatureScript : public UnitScript, public UpdatableScript<Creature> { protected: @@ -444,7 +436,7 @@ class CreatureScript : public UnitScript, public UpdatableScript<Creature> virtual CreatureAI* GetAI(Creature* /*creature*/) const { return NULL; } }; -class GameObjectScript : public ScriptObject, public UpdatableScript<GameObject> +class TC_GAME_API GameObjectScript : public ScriptObject, public UpdatableScript<GameObject> { protected: @@ -489,7 +481,7 @@ class GameObjectScript : public ScriptObject, public UpdatableScript<GameObject> virtual GameObjectAI* GetAI(GameObject* /*go*/) const { return NULL; } }; -class AreaTriggerScript : public ScriptObject +class TC_GAME_API AreaTriggerScript : public ScriptObject { protected: @@ -501,7 +493,7 @@ class AreaTriggerScript : public ScriptObject virtual bool OnTrigger(Player* /*player*/, AreaTriggerEntry const* /*trigger*/) { return false; } }; -class BattlegroundScript : public ScriptObject +class TC_GAME_API BattlegroundScript : public ScriptObject { protected: @@ -513,7 +505,7 @@ class BattlegroundScript : public ScriptObject virtual Battleground* GetBattleground() const = 0; }; -class OutdoorPvPScript : public ScriptObject +class TC_GAME_API OutdoorPvPScript : public ScriptObject { protected: @@ -525,7 +517,7 @@ class OutdoorPvPScript : public ScriptObject virtual OutdoorPvP* GetOutdoorPvP() const = 0; }; -class CommandScript : public ScriptObject +class TC_GAME_API CommandScript : public ScriptObject { protected: @@ -537,7 +529,7 @@ class CommandScript : public ScriptObject virtual std::vector<ChatCommand> GetCommands() const = 0; }; -class WeatherScript : public ScriptObject, public UpdatableScript<Weather> +class TC_GAME_API WeatherScript : public ScriptObject, public UpdatableScript<Weather> { protected: @@ -549,7 +541,7 @@ class WeatherScript : public ScriptObject, public UpdatableScript<Weather> virtual void OnChange(Weather* /*weather*/, WeatherState /*state*/, float /*grade*/) { } }; -class AuctionHouseScript : public ScriptObject +class TC_GAME_API AuctionHouseScript : public ScriptObject { protected: @@ -570,7 +562,7 @@ class AuctionHouseScript : public ScriptObject virtual void OnAuctionExpire(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } }; -class ConditionScript : public ScriptObject +class TC_GAME_API ConditionScript : public ScriptObject { protected: @@ -582,7 +574,7 @@ class ConditionScript : public ScriptObject virtual bool OnConditionCheck(Condition const* /*condition*/, ConditionSourceInfo& /*sourceInfo*/) { return true; } }; -class VehicleScript : public ScriptObject +class TC_GAME_API VehicleScript : public ScriptObject { protected: @@ -609,14 +601,14 @@ class VehicleScript : public ScriptObject virtual void OnRemovePassenger(Vehicle* /*veh*/, Unit* /*passenger*/) { } }; -class DynamicObjectScript : public ScriptObject, public UpdatableScript<DynamicObject> +class TC_GAME_API DynamicObjectScript : public ScriptObject, public UpdatableScript<DynamicObject> { protected: DynamicObjectScript(const char* name); }; -class TransportScript : public ScriptObject, public UpdatableScript<Transport> +class TC_GAME_API TransportScript : public ScriptObject, public UpdatableScript<Transport> { protected: @@ -637,7 +629,7 @@ class TransportScript : public ScriptObject, public UpdatableScript<Transport> virtual void OnRelocate(Transport* /*transport*/, uint32 /*waypointId*/, uint32 /*mapId*/, float /*x*/, float /*y*/, float /*z*/) { } }; -class AchievementCriteriaScript : public ScriptObject +class TC_GAME_API AchievementCriteriaScript : public ScriptObject { protected: @@ -649,7 +641,7 @@ class AchievementCriteriaScript : public ScriptObject virtual bool OnCheck(Player* source, Unit* target) = 0; }; -class PlayerScript : public UnitScript +class TC_GAME_API PlayerScript : public UnitScript { protected: @@ -746,7 +738,7 @@ class PlayerScript : public UnitScript virtual void OnQuestStatusChange(Player* /*player*/, uint32 /*questId*/, QuestStatus /*status*/) { } }; -class AccountScript : public ScriptObject +class TC_GAME_API AccountScript : public ScriptObject { protected: @@ -773,7 +765,7 @@ class AccountScript : public ScriptObject virtual void OnFailedPasswordChange(uint32 /*accountId*/) {} }; -class GuildScript : public ScriptObject +class TC_GAME_API GuildScript : public ScriptObject { protected: @@ -814,7 +806,7 @@ class GuildScript : public ScriptObject virtual void OnBankEvent(Guild* /*guild*/, uint8 /*eventType*/, uint8 /*tabId*/, ObjectGuid::LowType /*playerGuid*/, uint32 /*itemOrMoney*/, uint16 /*itemStackCount*/, uint8 /*destTabId*/) { } }; -class GroupScript : public ScriptObject +class TC_GAME_API GroupScript : public ScriptObject { protected: @@ -838,20 +830,8 @@ class GroupScript : public ScriptObject virtual void OnDisband(Group* /*group*/) { } }; -// Placed here due to ScriptRegistry::AddScript dependency. -#define sScriptMgr ScriptMgr::instance() - -// namespace -// { - typedef std::vector<ScriptObject*> UnusedScriptContainer; - typedef std::list<std::string> UnusedScriptNamesContainer; - - extern UnusedScriptContainer UnusedScripts; - extern UnusedScriptNamesContainer UnusedScriptNames; -// } - // Manages registration, loading, and execution of scripts. -class ScriptMgr +class TC_GAME_API ScriptMgr { friend class ScriptObject; @@ -859,32 +839,61 @@ class ScriptMgr ScriptMgr(); virtual ~ScriptMgr(); + void FillSpellSummary(); + void LoadDatabase(); + + void IncreaseScriptCount() { ++_scriptCount; } + void DecreaseScriptCount() { --_scriptCount; } + public: /* Initialization */ - static ScriptMgr* instance() - { - static ScriptMgr instance; - return &instance; - } + static ScriptMgr* instance(); void Initialize(); - void LoadDatabase(); - void FillSpellSummary(); - - const char* ScriptsVersion() const { return "Integrated Trinity Scripts"; } - void IncrementScriptCount() { ++_scriptCount; } uint32 GetScriptCount() const { return _scriptCount; } + typedef void(*ScriptLoaderCallbackType)(); + + /// Sets the script loader callback which is invoked to load scripts + /// (Workaround for circular dependency game <-> scripts) + void SetScriptLoader(ScriptLoaderCallbackType script_loader_callback) + { + _script_loader_callback = script_loader_callback; + } + + public: /* Script contexts */ + /// Set the current script context, which allows the ScriptMgr + /// to accept new scripts in this context. + /// Requires a SwapScriptContext() call afterwards to load the new scripts. + void SetScriptContext(std::string const& context); + /// Returns the current script context. + std::string const& GetCurrentScriptContext() const { return _currentContext; } + /// Releases all scripts associated with the given script context immediately. + /// Requires a SwapScriptContext() call afterwards to finish the unloading. + void ReleaseScriptContext(std::string const& context); + /// Executes all changed introduced by SetScriptContext and ReleaseScriptContext. + /// It is possible to combine multiple SetScriptContext and ReleaseScriptContext + /// calls for better performance (bulk changes). + void SwapScriptContext(bool initialize = false); + + /// Returns the context name of the static context provided by the worldserver + static std::string const& GetNameOfStaticContext(); + + /// Acquires a strong module reference to the module containing the given script name, + /// which prevents the shared library which contains the script from unloading. + /// The shared library is lazy unloaded as soon as all references to it are released. + std::shared_ptr<ModuleReference> AcquireModuleReferenceOfScriptName( + std::string const& scriptname) const; + public: /* Unloading */ void Unload(); - void UnloadUnusedScripts(); public: /* SpellScriptLoader */ void CreateSpellScripts(uint32 spellId, std::list<SpellScript*>& scriptVector); void CreateAuraScripts(uint32 spellId, std::list<AuraScript*>& scriptVector); - void CreateSpellScriptLoaders(uint32 spellId, std::vector<std::pair<SpellScriptLoader*, std::multimap<uint32, uint32>::iterator> >& scriptVector); + SpellScriptLoader* GetSpellScriptLoader(uint32 scriptId); public: /* ServerScript */ @@ -894,7 +903,6 @@ class ScriptMgr void OnSocketClose(std::shared_ptr<WorldSocket> socket); void OnPacketReceive(WorldSession* session, WorldPacket const& packet); void OnPacketSend(WorldSession* session, WorldPacket const& packet); - void OnUnknownPacketReceive(WorldSession* session, WorldPacket const& packet); public: /* WorldScript */ @@ -1098,19 +1106,14 @@ class ScriptMgr void ModifyMeleeDamage(Unit* target, Unit* attacker, uint32& damage); void ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& damage); - public: /* Scheduled scripts */ - - uint32 IncreaseScheduledScriptsCount() { return ++_scheduledScripts; } - uint32 DecreaseScheduledScriptCount() { return --_scheduledScripts; } - uint32 DecreaseScheduledScriptCount(size_t count) { return _scheduledScripts -= count; } - bool IsScriptScheduled() const { return _scheduledScripts > 0; } - private: - uint32 _scriptCount; - //atomic op counter for active scripts amount - std::atomic<uint32> _scheduledScripts; + ScriptLoaderCallbackType _script_loader_callback; + + std::string _currentContext; }; +#define sScriptMgr ScriptMgr::instance() + #endif diff --git a/src/server/game/Scripting/ScriptReloadMgr.cpp b/src/server/game/Scripting/ScriptReloadMgr.cpp new file mode 100644 index 00000000000..b0c9b6821d2 --- /dev/null +++ b/src/server/game/Scripting/ScriptReloadMgr.cpp @@ -0,0 +1,1641 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ScriptReloadMgr.h" +#include "Errors.h" + +#ifndef TRINITY_API_USE_DYNAMIC_LINKING + +// This method should never be called +std::shared_ptr<ModuleReference> + ScriptReloadMgr::AcquireModuleReferenceOfContext(std::string const& /*context*/) +{ + WPAbort(); +} + +// Returns the empty implemented ScriptReloadMgr +ScriptReloadMgr* ScriptReloadMgr::instance() +{ + static ScriptReloadMgr instance; + return &instance; +} + +#else + +#include <algorithm> +#include <regex> +#include <vector> +#include <future> +#include <memory> +#include <fstream> +#include <type_traits> +#include <unordered_set> +#include <unordered_map> + +#include <boost/algorithm/string/replace.hpp> +#include <boost/filesystem.hpp> +#include <boost/system/system_error.hpp> + +#include "efsw/efsw.hpp" + +#include "Log.h" +#include "Config.h" +#include "BuiltInConfig.h" +#include "ScriptMgr.h" +#include "SHA1.h" +#include "StartProcess.h" +#include "MPSCQueue.h" +#include "GitRevision.h" + +namespace fs = boost::filesystem; + +#ifdef _WIN32 + #include <windows.h> + #define HOTSWAP_PLATFORM_REQUIRES_CACHING +#else // Posix + #include <dlfcn.h> + // #define HOTSWAP_PLATFORM_REQUIRES_CACHING +#endif + +// Promote the sScriptReloadMgr to a HotSwapScriptReloadMgr +// in this compilation unit. +#undef sScriptReloadMgr +#define sScriptReloadMgr static_cast<HotSwapScriptReloadMgr*>(ScriptReloadMgr::instance()) + +// Returns "" on Windows and "lib" on posix. +static char const* GetSharedLibraryPrefix() +{ +#ifdef _WIN32 + return ""; +#else // Posix + return "lib"; +#endif +} + +// Returns "dll" on Windows and "so" on posix. +static char const* GetSharedLibraryExtension() +{ +#ifdef _WIN32 + return "dll"; +#else // Posix + return "so"; +#endif +} + +#ifdef _WIN32 +typedef HMODULE HandleType; +#else // Posix +typedef void* HandleType; +#endif + +static fs::path GetDirectoryOfExecutable() +{ + ASSERT((!sConfigMgr->GetArguments().empty()), + "Expected the arguments to contain at least 1 element!"); + + fs::path path(sConfigMgr->GetArguments()[0]); + if (path.is_absolute()) + return path.parent_path(); + else + return fs::absolute(path).parent_path(); +} + +class SharedLibraryUnloader +{ +public: + explicit SharedLibraryUnloader(fs::path path) + : path_(std::move(path)) { } + SharedLibraryUnloader(fs::path path, Optional<fs::path> cache_path) + : path_(std::move(path)), cache_path_(std::move(cache_path)) { } + + void operator() (HandleType handle) const + { + // Unload the associated shared library. +#ifdef _WIN32 + bool success = (FreeLibrary(handle) != 0); +#else // Posix + bool success = (dlclose(handle) == 0); +#endif + + if (!success) + { + TC_LOG_ERROR("scripts.hotswap", "Failed to unload (syscall) the shared library \"%s\".", + path_.generic_string().c_str()); + + return; + } + + /// When the shared library was cached delete it's shared version + if (cache_path_) + { + boost::system::error_code error; + if (!fs::remove(*cache_path_, error)) + { + TC_LOG_ERROR("scripts.hotswap", "Failed to delete the cached shared library \"%s\" (%s).", + cache_path_->generic_string().c_str(), error.message().c_str()); + + return; + } + + TC_LOG_TRACE("scripts.hotswap", "Lazy unloaded the shared library \"%s\" " + "and deleted it's cached version at \"%s\"", + path_.generic_string().c_str(), cache_path_->generic_string().c_str()); + } + else + { + TC_LOG_TRACE("scripts.hotswap", "Lazy unloaded the shared library \"%s\".", + path_.generic_string().c_str()); + } + } + +private: + fs::path const path_; + Optional<fs::path> const cache_path_; +}; + +typedef std::unique_ptr<typename std::remove_pointer<HandleType>::type, SharedLibraryUnloader> HandleHolder; + +typedef char const* (*GetScriptModuleRevisionHashType)(); +typedef void (*AddScriptsType)(); +typedef char const* (*GetScriptModuleType)(); +typedef char const* (*GetBuildDirectiveType)(); + +class ScriptModule + : public ModuleReference +{ +public: + explicit ScriptModule(HandleHolder handle, GetScriptModuleRevisionHashType getScriptModuleRevisionHash, + AddScriptsType addScripts, GetScriptModuleType getScriptModule, + GetBuildDirectiveType getBuildDirective, fs::path const& path) + : _handle(std::forward<HandleHolder>(handle)), _getScriptModuleRevisionHash(getScriptModuleRevisionHash), + _addScripts(addScripts), _getScriptModule(getScriptModule), + _getBuildDirective(getBuildDirective), _path(path) { } + + ScriptModule(ScriptModule const&) = delete; + ScriptModule(ScriptModule&& right) = delete; + + ScriptModule& operator= (ScriptModule const&) = delete; + ScriptModule& operator= (ScriptModule&& right) = delete; + + static Optional<std::shared_ptr<ScriptModule>> + CreateFromPath(fs::path const& path, Optional<fs::path> cache_path); + + static void ScheduleDelayedDelete(ScriptModule* module); + + char const* GetScriptModuleRevisionHash() const override + { + return _getScriptModuleRevisionHash(); + } + + void AddScripts() const + { + return _addScripts(); + } + + char const* GetScriptModule() const override + { + return _getScriptModule(); + } + + char const* GetBuildDirective() const + { + return _getBuildDirective(); + } + + fs::path const& GetModulePath() const override + { + return _path; + } + +private: + HandleHolder _handle; + + GetScriptModuleRevisionHashType _getScriptModuleRevisionHash; + AddScriptsType _addScripts; + GetScriptModuleType _getScriptModule; + GetBuildDirectiveType _getBuildDirective; + + fs::path _path; +}; + +template<typename Fn> +static bool GetFunctionFromSharedLibrary(HandleType handle, std::string const& name, Fn& fn) +{ +#ifdef _WIN32 + fn = reinterpret_cast<Fn>(GetProcAddress(handle, name.c_str())); +#else // Posix + fn = reinterpret_cast<Fn>(dlsym(handle, name.c_str())); +#endif + return fn != nullptr; +} + +// Load a shared library from the given path. +Optional<std::shared_ptr<ScriptModule>> + ScriptModule::CreateFromPath(fs::path const& path, Optional<fs::path> cache_path) +{ + auto const load_path = [&] () -> fs::path { + if (cache_path) + return *cache_path; + else + return path; + }(); + +#ifdef _WIN32 + HandleType handle = LoadLibrary(load_path.generic_string().c_str()); +#else // Posix + HandleType handle = dlopen(load_path.generic_string().c_str(), RTLD_LAZY); +#endif + + if (!handle) + { + if (cache_path) + { + TC_LOG_ERROR("scripts.hotswap", "Could not dynamic load the shared library \"%s\" " + "(the library is cached at %s)", + path.generic_string().c_str(), cache_path->generic_string().c_str()); + } + else + { + TC_LOG_ERROR("scripts.hotswap", "Could not dynamic load the shared library \"%s\".", + path.generic_string().c_str()); + } + + return boost::none; + } + + // Use RAII to release the library on failure. + HandleHolder holder(handle, SharedLibraryUnloader(path, std::move(cache_path))); + + GetScriptModuleRevisionHashType getScriptModuleRevisionHash; + AddScriptsType addScripts; + GetScriptModuleType getScriptModule; + GetBuildDirectiveType getBuildDirective; + + if (GetFunctionFromSharedLibrary(handle, "GetScriptModuleRevisionHash", getScriptModuleRevisionHash) && + GetFunctionFromSharedLibrary(handle, "AddScripts", addScripts) && + GetFunctionFromSharedLibrary(handle, "GetScriptModule", getScriptModule) && + GetFunctionFromSharedLibrary(handle, "GetBuildDirective", getBuildDirective)) + { + auto module = new ScriptModule(std::move(holder), getScriptModuleRevisionHash, + addScripts, getScriptModule, getBuildDirective, path); + + // Unload the module at the next update tick as soon as all references are removed + return std::shared_ptr<ScriptModule>(module, ScheduleDelayedDelete); + } + else + { + TC_LOG_ERROR("scripts.hotswap", "Could not extract all required functions from the shared library \"%s\"!", + path.generic_string().c_str()); + + return boost::none; + } +} + +static bool HasValidScriptModuleName(std::string const& name) +{ + // Detects scripts_NAME.dll's / .so's + static std::regex const regex( + Trinity::StringFormat("^%s[sS]cripts_[a-zA-Z0-9_]+\\.%s$", + GetSharedLibraryPrefix(), + GetSharedLibraryExtension())); + + return std::regex_match(name, regex); +} + +/// File watcher responsible for watching shared libraries +class LibraryUpdateListener : public efsw::FileWatchListener +{ +public: + LibraryUpdateListener() { } + virtual ~LibraryUpdateListener() { } + + void handleFileAction(efsw::WatchID /*watchid*/, std::string const& dir, + std::string const& filename, efsw::Action action, std::string oldFilename = "") final override; +}; + +static LibraryUpdateListener libraryUpdateListener; + +/// File watcher responsible for watching source files +class SourceUpdateListener : public efsw::FileWatchListener +{ + fs::path const path_; + + std::string const script_module_name_; + + efsw::WatchID const watcher_id_; + +public: + explicit SourceUpdateListener(fs::path path, std::string script_module_name); + + virtual ~SourceUpdateListener(); + + void handleFileAction(efsw::WatchID /*watchid*/, std::string const& dir, + std::string const& filename, efsw::Action action, std::string oldFilename = "") final override; +}; + +namespace std +{ + template <> + struct hash<fs::path> + { + hash<string> hasher; + + std::size_t operator()(fs::path const& key) const + { + return hasher(key.generic_string()); + } + }; +} + +/// Invokes a synchronous CMake process with the given arguments +template<typename... T> +static int InvokeCMakeCommand(T&&... args) +{ + auto const executable = BuiltInConfig::GetCMakeCommand(); + return Trinity::StartProcess(executable, { + executable, + std::forward<T>(args)... + }, "scripts.hotswap"); +} + +/// Invokes an asynchronous CMake process with the given arguments +template<typename... T> +static std::shared_ptr<Trinity::AsyncProcessResult> InvokeAsyncCMakeCommand(T&&... args) +{ + auto const executable = BuiltInConfig::GetCMakeCommand(); + return Trinity::StartAsyncProcess(executable, { + executable, + std::forward<T>(args)... + }, "scripts.hotswap"); +} + +/// Calculates the C++ project name of the given module which is +/// the lowercase string of scripts_${module}. +static std::string CalculateScriptModuleProjectName(std::string const& module) +{ + std::string module_project = "scripts_" + module; + std::transform(module_project.begin(), module_project.end(), + module_project.begin(), ::tolower); + + return module_project; +} + +/// Returns false when there isn't any attached debugger to the process which +/// could block the rebuild of new shared libraries. +static bool IsDebuggerBlockingRebuild() +{ +#ifdef _WIN32 + if (IsDebuggerPresent()) + return true; +#endif + return false; +} + +/// ScriptReloadMgr which is used when dynamic linking is enabled +/// +/// This class manages shared library loading/unloading through watching +/// the script module directory. Loaded shared libraries are mirrored +/// into a cache subdirectory to allow lazy unloading as long as +/// the shared library is still used which is useful for scripts +/// which can't be instantly replaced like spells or instances. +/// Several modules which reference different versions can be kept loaded +/// to serve scripts of different versions to entities and spells. +/// +/// Also this class invokes rebuilds as soon as the source of loaded +/// scripts change and installs the modules correctly through CMake. +class HotSwapScriptReloadMgr final + : public ScriptReloadMgr +{ + friend class ScriptReloadMgr; + friend class SourceUpdateListener; + + /// Reflects a queued change on a shared library or shared library + /// which is waiting for processing + enum class ChangeStateRequest : uint8 + { + CHANGE_REQUEST_ADDED, + CHANGE_REQUEST_MODIFIED, + CHANGE_REQUEST_REMOVED + }; + + /// Reflects a running job of an invoked asynchronous external process + enum class BuildJobType : uint8 + { + BUILD_JOB_NONE, + BUILD_JOB_RERUN_CMAKE, + BUILD_JOB_COMPILE, + BUILD_JOB_INSTALL, + }; + + // Represents a job which was invoked through a source or shared library change + class BuildJob + { + // Script module which is processed in the current running job + std::string script_module_name_; + // The C++ project name of the module which is processed + std::string script_module_project_name_; + // The build directive of the current module which is processed + // like "Release" or "Debug". The build directive from the + // previous same module is used if there was any. + std::string script_module_build_directive_; + // The time where the build job started + uint32 start_time_; + + // Type of the current running job + BuildJobType type_; + // The async process result of the current job + std::shared_ptr<Trinity::AsyncProcessResult> async_result_; + + public: + explicit BuildJob(std::string script_module_name, std::string script_module_project_name, + std::string script_module_build_directive) + : script_module_name_(std::move(script_module_name)), + script_module_project_name_(std::move(script_module_project_name)), + script_module_build_directive_(std::move(script_module_build_directive)), + start_time_(getMSTime()), type_(BuildJobType::BUILD_JOB_NONE) { } + + bool IsValid() const + { + return type_ != BuildJobType::BUILD_JOB_NONE; + } + + std::string const& GetModuleName() const { return script_module_name_; } + + std::string const& GetProjectName() const { return script_module_project_name_; } + + std::string const& GetBuildDirective() const { return script_module_build_directive_; } + + uint32 GetTimeFromStart() const { return GetMSTimeDiffToNow(start_time_); } + + BuildJobType GetType() const { return type_; } + + std::shared_ptr<Trinity::AsyncProcessResult> const& GetProcess() const + { + ASSERT(async_result_, "Tried to access an empty process handle!"); + return async_result_; + } + + /// Updates the current running job with the given type and async result + void UpdateCurrentJob(BuildJobType type, + std::shared_ptr<Trinity::AsyncProcessResult> async_result) + { + ASSERT(type != BuildJobType::BUILD_JOB_NONE, "None isn't allowed here!"); + ASSERT(async_result, "The async result must not be empty!"); + + type_ = type; + async_result_ = std::move(async_result); + } + }; + + /// Base class for lockfree asynchronous messages to the script reloader + class ScriptReloaderMessage + { + public: + virtual ~ScriptReloaderMessage() { } + + /// Invoke this function to run a message thread safe on the reloader + virtual void operator() (HotSwapScriptReloadMgr* reloader) = 0; + }; + + /// Implementation class which wraps functional types and dispatches + /// it in the overwritten implementation of the reloader messages. + template<typename T> + class ScriptReloaderMessageImplementation + : public ScriptReloaderMessage + { + T dispatcher_; + + public: + explicit ScriptReloaderMessageImplementation(T dispatcher) + : dispatcher_(std::move(dispatcher)) { } + + void operator() (HotSwapScriptReloadMgr* reloader) final override + { + dispatcher_(reloader); + } + }; + + /// Uses the given functional type and creates a asynchronous reloader + /// message on the heap, which requires deletion. + template<typename T> + auto MakeMessage(T&& dispatcher) + -> ScriptReloaderMessageImplementation<typename std::decay<T>::type>* + { + return new ScriptReloaderMessageImplementation<typename std::decay<T>::type> + (std::forward<T>(dispatcher)); + } + +public: + HotSwapScriptReloadMgr() + : _libraryWatcher(-1), _unique_library_name_counter(0), + _last_time_library_changed(0), _last_time_sources_changed(0), + _last_time_user_informed(0), terminate_early(false) { } + + virtual ~HotSwapScriptReloadMgr() + { + // Delete all messages + ScriptReloaderMessage* message; + while (_messages.Dequeue(message)) + delete message; + } + + /// Returns the absolute path to the script module directory + static fs::path GetLibraryDirectory() + { + // When an absolute path is given in the config use it, + // otherwise interpret paths relative to the executable. + fs::path path(sConfigMgr->GetStringDefault("HotSwap.ScriptDir", "scripts")); + if (path.is_absolute()) + return path; + else + return fs::absolute(path, GetDirectoryOfExecutable()); + } + + /// Returns the absolute path to the scripts directory in the source tree. + static fs::path GetSourceDirectory() + { + fs::path dir = BuiltInConfig::GetSourceDirectory(); + dir /= "src"; + dir /= "server"; + dir /= "scripts"; + return dir; + } + + /// Initializes the file watchers and loads all existing shared libraries + /// into the running server. + void Initialize() final override + { + if (!sWorld->getBoolConfig(CONFIG_HOTSWAP_ENABLED)) + return; + + if (BuiltInConfig::GetBuildDirectory().find(" ") != std::string::npos) + { + TC_LOG_ERROR("scripts.hotswap", "Your build directory path \"%s\" " + "contains spaces, which isn't allowed for compatibility reasons! " + "You need to create a build directory which doesn't contain any space character " + "in it's path!", + BuiltInConfig::GetBuildDirectory().c_str()); + + return; + } + + { + auto const library_directory = GetLibraryDirectory(); + if (!fs::exists(library_directory) || !fs::is_directory(library_directory)) + { + TC_LOG_ERROR("scripts.hotswap", "Library directory \"%s\" doesn't exist!.", + library_directory.generic_string().c_str()); + return; + } + } + + #ifdef HOTSWAP_PLATFORM_REQUIRES_CACHING + + temporary_cache_path_ = CalculateTemporaryCachePath(); + + // We use the boost filesystem function versions which accept + // an error code to prevent it from throwing exceptions. + boost::system::error_code code; + if ((!fs::exists(temporary_cache_path_, code) + || (fs::remove_all(temporary_cache_path_, code) > 0)) && + !fs::create_directory(temporary_cache_path_, code)) + { + TC_LOG_ERROR("scripts.hotswap", "Couldn't create the cache directory at \"%s\".", + temporary_cache_path_.generic_string().c_str()); + + return; + } + + // Used to silent compiler warnings + (void)code; + + #endif // #ifdef HOTSWAP_PLATFORM_REQUIRES_CACHING + + // Correct the CMake prefix when needed + if (sWorld->getBoolConfig(CONFIG_HOTSWAP_PREFIX_CORRECTION_ENABLED)) + DoCMakePrefixCorrectionIfNeeded(); + + InitializeDefaultLibraries(); + InitializeFileWatchers(); + } + + /// Needs to be called periodically from the worldserver loop + /// to invoke queued actions like module loading/unloading and script + /// compilation. + /// This method should be invoked from a thread safe point to + /// prevent misbehavior. + void Update() final override + { + // Consume all messages + ScriptReloaderMessage* message; + while (_messages.Dequeue(message)) + { + (*message)(this); + delete message; + } + + DispatchRunningBuildJobs(); + DispatchModuleChanges(); + } + + /// Unloads the manager and cancels all runnings jobs immediately + void Unload() final override + { + if (_libraryWatcher >= 0) + { + _fileWatcher.removeWatch(_libraryWatcher); + _libraryWatcher = -1; + } + + // If a build is in progress cancel it + if (_build_job) + { + _build_job->GetProcess()->Terminate(); + _build_job.reset(); + } + + // Release all strong references to script modules + // to trigger unload actions as early as possible, + // otherwise the worldserver will crash on exit. + _running_script_modules.clear(); + } + + /// Queue's a thread safe message to the reloader which is executed on + /// the next world server update tick. + template<typename T> + void QueueMessage(T&& message) + { + _messages.Enqueue(MakeMessage(std::forward<T>(message))); + } + + /// Queues an action which marks the given shared library as changed + /// which will add, unload or reload it at the next world update tick. + /// This method is thread safe. + void QueueSharedLibraryChanged(fs::path const& path) + { + _last_time_library_changed = getMSTime(); + _libraries_changed.insert(path); + } + + /// Queues a notification that a source file was added + /// This method is thread unsafe. + void QueueAddSourceFile(std::string const& module_name, fs::path const& path) + { + UpdateSourceChangeRequest(module_name, path, ChangeStateRequest::CHANGE_REQUEST_ADDED); + } + + /// Queues a notification that a source file was modified + /// This method is thread unsafe. + void QueueModifySourceFile(std::string const& module_name, fs::path const& path) + { + UpdateSourceChangeRequest(module_name, path, ChangeStateRequest::CHANGE_REQUEST_MODIFIED); + } + + /// Queues a notification that a source file was removed + /// This method is thread unsafe. + void QueueRemoveSourceFile(std::string const& module_name, fs::path const& path) + { + UpdateSourceChangeRequest(module_name, path, ChangeStateRequest::CHANGE_REQUEST_REMOVED); + } + +private: + // Loads all shared libraries which are contained in the + // scripts directory on startup. + void InitializeDefaultLibraries() + { + fs::path const libraryDirectory(GetLibraryDirectory()); + fs::directory_iterator const dir_end; + + uint32 count = 0; + + // Iterate through all shared libraries in the script directory and load it + for (fs::directory_iterator dir_itr(libraryDirectory); dir_itr != dir_end ; ++dir_itr) + if (fs::is_regular_file(dir_itr->path()) && HasValidScriptModuleName(dir_itr->path().filename().generic_string())) + { + TC_LOG_INFO("scripts.hotswap", "Loading script module \"%s\"...", + dir_itr->path().filename().generic_string().c_str()); + + // Don't swap the script context to do bulk loading + ProcessLoadScriptModule(dir_itr->path(), false); + ++count; + } + + TC_LOG_INFO("scripts.hotswap", ">> Loaded %u script modules.", count); + } + + // Initialize all enabled file watchers. + // Needs to be called after InitializeDefaultLibraries()! + void InitializeFileWatchers() + { + _libraryWatcher = _fileWatcher.addWatch(GetLibraryDirectory().generic_string(), &libraryUpdateListener, false); + if (_libraryWatcher >= 0) + { + TC_LOG_INFO("scripts.hotswap", ">> Library reloader is listening on \"%s\".", + GetLibraryDirectory().generic_string().c_str()); + } + else + { + TC_LOG_ERROR("scripts.hotswap", "Failed to initialize the library reloader on \"%s\".", + GetLibraryDirectory().generic_string().c_str()); + } + + _fileWatcher.watch(); + } + + static fs::path CalculateTemporaryCachePath() + { + auto path = fs::temp_directory_path(); + path /= Trinity::StringFormat("tc_script_cache_%s_%s", + GitRevision::GetBranch(), + CalculateSHA1Hash(sConfigMgr->GetFilename()).c_str()); + + return path; + } + + fs::path GenerateUniquePathForLibraryInCache(fs::path path) + { + ASSERT(!temporary_cache_path_.empty(), + "The temporary cache path wasn't set!"); + + // Create the cache path and increment the library counter to use an unique name for each library + auto cache_path = temporary_cache_path_; + cache_path /= Trinity::StringFormat("%s.%u%s", + path.stem().generic_string().c_str(), + _unique_library_name_counter++, + path.extension().generic_string().c_str()); + + return cache_path; + } + + /// Updates the current state of the given source path + void UpdateSourceChangeRequest(std::string const& module_name, + fs::path const& path, + ChangeStateRequest state) + { + _last_time_sources_changed = getMSTime(); + + // Write when there is no module with the given name known + auto module_itr = _sources_changed.find(module_name); + + // When the file was modified it's enough to mark the module as + // dirty by initializing the associated map. + if (module_itr == _sources_changed.end()) + module_itr = _sources_changed.insert(std::make_pair( + module_name, decltype(_sources_changed)::mapped_type{})).first; + + // Leave when the file was just modified as explained above + if (state == ChangeStateRequest::CHANGE_REQUEST_MODIFIED) + return; + + // Insert when the given path isn't existent + auto const itr = module_itr->second.find(path); + if (itr == module_itr->second.end()) + { + module_itr->second.insert(std::make_pair(path, state)); + return; + } + + ASSERT((itr->second == ChangeStateRequest::CHANGE_REQUEST_ADDED) + || (itr->second == ChangeStateRequest::CHANGE_REQUEST_REMOVED), + "Stored value is invalid!"); + + ASSERT((state == ChangeStateRequest::CHANGE_REQUEST_ADDED) + || (state == ChangeStateRequest::CHANGE_REQUEST_REMOVED), + "The given state is invalid!"); + + ASSERT(state != itr->second, + "Tried to apply a state which is stored already!"); + + module_itr->second.erase(itr); + } + + /// Called periodically on the worldserver tick to process all + /// load/unload/reload requests of shared libraries. + void DispatchModuleChanges() + { + // When there are no libraries to change return + if (_libraries_changed.empty()) + return; + + // Wait some time after changes to catch bulk changes + if (GetMSTimeDiffToNow(_last_time_library_changed) < 500) + return; + + for (auto const& path : _libraries_changed) + { + bool const is_running = + _running_script_module_names.find(path) != _running_script_module_names.end(); + + bool const exists = fs::exists(path); + + if (is_running) + { + if (exists) + ProcessReloadScriptModule(path); + else + ProcessUnloadScriptModule(path); + } + else if (exists) + ProcessLoadScriptModule(path); + } + + _libraries_changed.clear(); + } + + void ProcessLoadScriptModule(fs::path const& path, bool swap_context = true) + { + ASSERT(_running_script_module_names.find(path) == _running_script_module_names.end(), + "Can't load a module which is running already!"); + + Optional<fs::path> cache_path; + + #ifdef HOTSWAP_PLATFORM_REQUIRES_CACHING + + // Copy the shared library into a cache on platforms which lock files on use (windows). + cache_path = GenerateUniquePathForLibraryInCache(path); + + { + boost::system::error_code code; + fs::copy_file(path, *cache_path, fs::copy_option::fail_if_exists, code); + if (code) + { + TC_LOG_FATAL("scripts.hotswap", ">> Failed to create cache entry for module " + "\"%s\" at \"%s\" with reason (\"%s\")!", + path.filename().generic_string().c_str(), cache_path->generic_string().c_str(), + code.message().c_str()); + + // Find a better solution for this but it's much better + // to start the core without scripts + std::this_thread::sleep_for(std::chrono::seconds(5)); + ABORT(); + return; + } + + TC_LOG_TRACE("scripts.hotswap", ">> Copied the shared library \"%s\" to \"%s\" for caching.", + path.filename().generic_string().c_str(), cache_path->generic_string().c_str()); + } + + #endif // #ifdef HOTSWAP_PLATFORM_REQUIRES_CACHING + + auto module = ScriptModule::CreateFromPath(path, cache_path); + if (!module) + { + TC_LOG_FATAL("scripts.hotswap", ">> Failed to load script module \"%s\"!", + path.filename().generic_string().c_str()); + + // Find a better solution for this but it's much better + // to start the core without scripts + std::this_thread::sleep_for(std::chrono::seconds(5)); + ABORT(); + return; + } + + // Limit the git revision hash to 7 characters. + std::string module_revision((*module)->GetScriptModuleRevisionHash()); + if (module_revision.size() >= 7) + module_revision = module_revision.substr(0, 7); + + std::string const module_name = (*module)->GetScriptModule(); + TC_LOG_INFO("scripts.hotswap", ">> Loaded script module \"%s\" (\"%s\" - %s).", + path.filename().generic_string().c_str(), module_name.c_str(), module_revision.c_str()); + + if (module_revision.empty()) + { + TC_LOG_WARN("scripts.hotswap", ">> Script module \"%s\" has an empty revision hash!", + path.filename().generic_string().c_str()); + } + else + { + // Trim the revision hash + std::string my_revision_hash = GitRevision::GetHash(); + std::size_t const trim = std::min(module_revision.size(), my_revision_hash.size()); + my_revision_hash = my_revision_hash.substr(0, trim); + module_revision = module_revision.substr(0, trim); + + if (my_revision_hash != module_revision) + { + TC_LOG_WARN("scripts.hotswap", ">> Script module \"%s\" has a different revision hash! " + "Binary incompatibility could lead to unknown behaviour!", path.filename().generic_string().c_str()); + } + } + + { + auto const itr = _running_script_modules.find(module_name); + if (itr != _running_script_modules.end()) + { + TC_LOG_ERROR("scripts.hotswap", ">> Attempt to load a module twice \"%s\" (loaded module is at %s)!", + path.generic_string().c_str(), itr->second.first->GetModulePath().generic_string().c_str()); + + return; + } + } + + // Create the source listener + auto listener = Trinity::make_unique<SourceUpdateListener>( + sScriptReloadMgr->GetSourceDirectory() / module_name, + module_name); + + // Store the module + _known_modules_build_directives.insert(std::make_pair(module_name, (*module)->GetBuildDirective())); + _running_script_modules.insert(std::make_pair(module_name, + std::make_pair(*module, std::move(listener)))); + _running_script_module_names.insert(std::make_pair(path, module_name)); + + // Process the script loading after the module was registered correctly (#17557). + sScriptMgr->SetScriptContext(module_name); + (*module)->AddScripts(); + TC_LOG_TRACE("scripts.hotswap", ">> Registered all scripts of module %s.", module_name.c_str()); + + if (swap_context) + sScriptMgr->SwapScriptContext(); + } + + void ProcessReloadScriptModule(fs::path const& path) + { + ProcessUnloadScriptModule(path, false); + ProcessLoadScriptModule(path); + } + + void ProcessUnloadScriptModule(fs::path const& path, bool finish = true) + { + auto const itr = _running_script_module_names.find(path); + + ASSERT(itr != _running_script_module_names.end(), + "Can't unload a module which isn't running!"); + + // Unload the script context + sScriptMgr->ReleaseScriptContext(itr->second); + + if (finish) + sScriptMgr->SwapScriptContext(); + + TC_LOG_INFO("scripts.hotswap", "Released script module \"%s\" (\"%s\")...", + path.filename().generic_string().c_str(), itr->second.c_str()); + + // Unload the script module + auto ref = _running_script_modules.find(itr->second); + ASSERT(ref != _running_script_modules.end() && + "Expected the script reference to be present!"); + + // Yield a message when there are other owning references to + // the module which prevents it from unloading. + // The module will be unloaded once all scripts provided from the module + // are destroyed. + if (!ref->second.first.unique()) + { + TC_LOG_INFO("scripts.hotswap", + "Script module %s is still used by %lu spell, aura or instance scripts. " + "Will lazy unload the module once all scripts stopped using it, " + "to use the latest version of an edited script unbind yourself from " + "the instance or re-cast the spell.", + ref->second.first->GetScriptModule(), ref->second.first.use_count() - 1); + } + + // Remove the owning reference from the reloader + _running_script_modules.erase(ref); + _running_script_module_names.erase(itr); + } + + /// Called periodically on the worldserver tick to process all recompile + /// requests. This method invokes one build or install job at the time + void DispatchRunningBuildJobs() + { + if (_build_job) + { + // Terminate the current build job when an associated source was changed + // while compiling and the terminate early option is enabled. + if (sWorld->getBoolConfig(CONFIG_HOTSWAP_EARLY_TERMINATION_ENABLED)) + { + if (!terminate_early && _sources_changed.find(_build_job->GetModuleName()) != _sources_changed.end()) + { + /* + FIXME: Currently crashes the server + TC_LOG_INFO("scripts.hotswap", "Terminating the running build of module \"%s\"...", + _build_job->GetModuleName().c_str()); + + _build_job->GetProcess()->Terminate(); + _build_job.reset(); + + // Continue with the default execution path + DispatchRunningBuildJobs(); + return; + */ + + terminate_early = true; + return; + } + } + + // Wait for the current build job to finish, if the job finishes in time + // evaluate it and continue with the next one. + if (_build_job->GetProcess()->GetFutureResult(). + wait_for(std::chrono::seconds(0)) == std::future_status::ready) + ProcessReadyBuildJob(); + else + return; // Return when the job didn't finish in time + + // Skip this cycle when the previous job scheduled a new one + if (_build_job) + return; + } + + // Avoid burst updates through waiting for a short time after changes + if ((_last_time_sources_changed != 0) && + (GetMSTimeDiffToNow(_last_time_sources_changed) < 500)) + return; + + // If the changed sources are empty do nothing + if (_sources_changed.empty()) + return; + + // Wait until are attached debugger were detached. + if (IsDebuggerBlockingRebuild()) + { + if ((_last_time_user_informed == 0) || + (GetMSTimeDiffToNow(_last_time_user_informed) > 7500)) + { + _last_time_user_informed = getMSTime(); + + // Informs the user that the attached debugger is blocking the automatic script rebuild. + TC_LOG_INFO("scripts.hotswap", "Your attached debugger is blocking the TrinityCore " + "automatic script rebuild, please detach it!"); + } + + return; + } + + // Find all source files of a changed script module and removes + // it from the changed source list, invoke the build afterwards. + bool rebuild_buildfiles; + auto module_name = [&] + { + auto itr = _sources_changed.begin(); + auto name = itr->first; + rebuild_buildfiles = !itr->second.empty(); + + if (sLog->ShouldLog("scripts.hotswap", LogLevel::LOG_LEVEL_TRACE)) + for (auto const& entry : itr->second) + { + TC_LOG_TRACE("scripts.hotswap", "Source file %s was %s.", + entry.first.generic_string().c_str(), + ((entry.second == ChangeStateRequest::CHANGE_REQUEST_ADDED) ? + "added" : "removed")); + } + + _sources_changed.erase(itr); + return name; + }(); + + // Erase the added delete history all modules when we + // invoke a cmake rebuild since we add all + // added files of other modules to the build as well + if (rebuild_buildfiles) + { + for (auto& entry : _sources_changed) + entry.second.clear(); + } + + ASSERT(!module_name.empty(), + "The current module name is invalid!"); + + TC_LOG_INFO("scripts.hotswap", "Recompiling Module \"%s\"...", + module_name.c_str()); + + // Calculate the project name of the script module + auto project_name = CalculateScriptModuleProjectName(module_name); + + // Find the best build directive for the module + auto build_directive = [&] () -> std::string + { + auto directive = sConfigMgr->GetStringDefault("HotSwap.ReCompilerBuildType", ""); + if (!directive.empty()) + return directive; + + auto const itr = _known_modules_build_directives.find(module_name); + if (itr != _known_modules_build_directives.end()) + return itr->second; + else // If no build directive of the module was found use the one from the game library + return _BUILD_DIRECTIVE; + }(); + + // Initiate the new build job + _build_job = BuildJob(std::move(module_name), + std::move(project_name), std::move(build_directive)); + + // Rerun CMake when we need to recreate the build files + if (rebuild_buildfiles + && sWorld->getBoolConfig(CONFIG_HOTSWAP_BUILD_FILE_RECREATION_ENABLED)) + DoRerunCMake(); + else + DoCompileCurrentProcessedModule(); + } + + void ProcessReadyBuildJob() + { + ASSERT(_build_job->IsValid(), "Invalid build job!"); + + // Retrieve the result + auto const error = _build_job->GetProcess()->GetFutureResult().get(); + + if (terminate_early) + { + _build_job.reset(); + terminate_early = false; + return; + } + + switch (_build_job->GetType()) + { + case BuildJobType::BUILD_JOB_RERUN_CMAKE: + { + if (!error) + { + TC_LOG_INFO("scripts.hotswap", ">> Successfully updated the build files!"); + } + else + { + TC_LOG_INFO("scripts.hotswap", ">> Failed to update the build files at \"%s\", " + "it's possible that recently added sources are not included " + "in your next builds, rerun CMake manually.", + BuiltInConfig::GetBuildDirectory().c_str()); + } + // Continue with building the changes sources + DoCompileCurrentProcessedModule(); + return; + } + case BuildJobType::BUILD_JOB_COMPILE: + { + if (!error) // Build was successful + { + if (sWorld->getBoolConfig(CONFIG_HOTSWAP_INSTALL_ENABLED)) + { + // Continue with the installation when it's enabled + TC_LOG_INFO("scripts.hotswap", + ">> Successfully build module %s, continue with installing...", + _build_job->GetModuleName().c_str()); + + DoInstallCurrentProcessedModule(); + return; + } + + // Skip the installation because it's disabled in config + TC_LOG_INFO("scripts.hotswap", + ">> Successfully build module %s, skipped the installation.", + _build_job->GetModuleName().c_str()); + } + else // Build wasn't successful + { + TC_LOG_ERROR("scripts.hotswap", + ">> The build of module %s failed! See the log for details.", + _build_job->GetModuleName().c_str()); + } + break; + } + case BuildJobType::BUILD_JOB_INSTALL: + { + if (!error) + { + // Installation was successful + TC_LOG_INFO("scripts.hotswap", ">> Successfully installed module %s in %us", + _build_job->GetModuleName().c_str(), + _build_job->GetTimeFromStart() / IN_MILLISECONDS); + } + else + { + // Installation wasn't successful + TC_LOG_INFO("scripts.hotswap", + ">> The installation of module %s failed! See the log for details.", + _build_job->GetModuleName().c_str()); + } + break; + } + default: + break; + } + + // Clear the current job + _build_job.reset(); + } + + /// Reruns CMake asynchronously over the build directory + void DoRerunCMake() + { + ASSERT(_build_job, "There isn't any active build job!"); + + TC_LOG_INFO("scripts.hotswap", "Rerunning CMake because there were sources added or removed..."); + + _build_job->UpdateCurrentJob(BuildJobType::BUILD_JOB_RERUN_CMAKE, + InvokeAsyncCMakeCommand(BuiltInConfig::GetBuildDirectory())); + } + + /// Invokes a new build of the current active module job + void DoCompileCurrentProcessedModule() + { + ASSERT(_build_job, "There isn't any active build job!"); + + TC_LOG_INFO("scripts.hotswap", "Starting asynchronous build job for module %s...", + _build_job->GetModuleName().c_str()); + + _build_job->UpdateCurrentJob(BuildJobType::BUILD_JOB_COMPILE, + InvokeAsyncCMakeCommand( + "--build", BuiltInConfig::GetBuildDirectory(), + "--target", _build_job->GetProjectName(), + "--config", _build_job->GetBuildDirective())); + } + + /// Invokes a new asynchronous install of the current active module job + void DoInstallCurrentProcessedModule() + { + ASSERT(_build_job, "There isn't any active build job!"); + + TC_LOG_INFO("scripts.hotswap", "Starting asynchronous install job for module %s...", + _build_job->GetModuleName().c_str()); + + _build_job->UpdateCurrentJob(BuildJobType::BUILD_JOB_INSTALL, + InvokeAsyncCMakeCommand( + "-DCOMPONENT=" + _build_job->GetProjectName(), + "-DBUILD_TYPE=" + _build_job->GetBuildDirective(), + "-P", fs::absolute("cmake_install.cmake", + BuiltInConfig::GetBuildDirectory()).generic_string())); + } + + /// Sets the CMAKE_INSTALL_PREFIX variable in the CMake cache + /// to point to the current worldserver position, + /// since most users will forget this. + void DoCMakePrefixCorrectionIfNeeded() + { + TC_LOG_INFO("scripts.hotswap", "Correcting your CMAKE_INSTALL_PREFIX in \"%s\"...", + BuiltInConfig::GetBuildDirectory().c_str()); + + auto const cmake_cache_path = fs::absolute("CMakeCache.txt", + BuiltInConfig::GetBuildDirectory()); + + // Stop when the CMakeCache wasn't found + if (![&] + { + boost::system::error_code error; + if (!fs::exists(cmake_cache_path, error)) + { + TC_LOG_ERROR("scripts.hotswap", ">> CMake cache \"%s\" doesn't exist, " + "set the \"BuildDirectory\" option in your worldserver.conf to point" + "to your build directory!", + cmake_cache_path.generic_string().c_str()); + + return false; + } + else + return true; + }()) + return; + + TC_LOG_TRACE("scripts.hotswap", "Checking CMake cache (\"%s\") " + "for the correct CMAKE_INSTALL_PREFIX location...", + cmake_cache_path.generic_string().c_str()); + + std::string cmake_cache_content; + { + std::ifstream in(cmake_cache_path.generic_string()); + if (!in.is_open()) + { + TC_LOG_ERROR("scripts.hotswap", ">> Failed to read the CMake cache at \"%s\"!", + cmake_cache_path.generic_string().c_str()); + + return; + } + + std::ostringstream ss; + ss << in.rdbuf(); + cmake_cache_content = ss.str(); + + in.close(); + } + + static std::string const prefix_key = "CMAKE_INSTALL_PREFIX:PATH="; + + // Extract the value of CMAKE_INSTALL_PREFIX + auto begin = cmake_cache_content.find(prefix_key); + if (begin != std::string::npos) + { + begin += prefix_key.length(); + auto const end = cmake_cache_content.find("\n", begin); + if (end != std::string::npos) + { + fs::path value = cmake_cache_content.substr(begin, end - begin); + + auto current_path = fs::current_path(); + + #ifndef _WIN32 + // The worldserver location is ${CMAKE_INSTALL_PREFIX}/bin + // on all other platforms then windows + current_path = current_path.parent_path(); + #endif + + if (value != current_path) + { + // Prevent correction of the install prefix + // when we are starting the core from inside the build tree + bool const is_in_path = [&] + { + fs::path base = BuiltInConfig::GetBuildDirectory(); + fs::path branch = value; + while (!branch.empty()) + { + if (base == branch) + return true; + + branch = branch.parent_path(); + } + + return false; + }(); + + if (is_in_path) + return; + + TC_LOG_INFO("scripts.hotswap", ">> Found outdated CMAKE_INSTALL_PREFIX (\"%s\"), " + "worldserver is currently installed at %s...", + value.generic_string().c_str(), current_path.generic_string().c_str()); + } + else + { + TC_LOG_INFO("scripts.hotswap", ">> CMAKE_INSTALL_PREFIX is equal to the current path of execution."); + return; + } + } + } + + TC_LOG_INFO("scripts.hotswap", "Invoking CMake cache correction..."); + + auto const error = InvokeCMakeCommand( + "-DCMAKE_INSTALL_PREFIX:PATH=" + fs::current_path().generic_string(), + BuiltInConfig::GetBuildDirectory()); + + if (error) + { + TC_LOG_ERROR("scripts.hotswap", ">> Failed to update the CMAKE_INSTALL_PREFIX! " + "This could lead to unexpected behaviour!"); + } + else + { + TC_LOG_ERROR("scripts.hotswap", ">> Successfully corrected your CMAKE_INSTALL_PREFIX variable" + "to point at your current path of execution."); + } + } + + // File watcher instance and watcher ID's + efsw::FileWatcher _fileWatcher; + efsw::WatchID _libraryWatcher; + + // Unique library name counter which is used to + // generate unique names for every shared library version. + uint32 _unique_library_name_counter; + + // Queue which is used for thread safe message processing + MPSCQueue<ScriptReloaderMessage> _messages; + + // Change requests to load or unload shared libraries + std::unordered_set<fs::path /*path*/> _libraries_changed; + // The timestamp which indicates the last time a library was changed + uint32 _last_time_library_changed; + + // Contains all running script modules + // The associated shared libraries are unloaded immediately + // on loosing ownership through RAII. + std::unordered_map<std::string /*module name*/, + std::pair<std::shared_ptr<ScriptModule>, std::unique_ptr<SourceUpdateListener>> + > _running_script_modules; + // Container which maps the path of a shared library to it's module name + std::unordered_map<fs::path, std::string /*module name*/> _running_script_module_names; + // Container which maps the module name to it's last known build directive + std::unordered_map<std::string /*module name*/, std::string /*build directive*/> _known_modules_build_directives; + + // Modules which were changed and are queued for recompilation + std::unordered_map<std::string /*module*/, + std::unordered_map<fs::path /*path*/, ChangeStateRequest /*state*/>> _sources_changed; + // Tracks the time since the last module has changed to avoid burst updates + uint32 _last_time_sources_changed; + + // Tracks the last timestamp the user was informed about a certain repeating event. + uint32 _last_time_user_informed; + + // Represents the current build job which is in progress + Optional<BuildJob> _build_job; + + // Is true when the build job dispatcher should stop after + // the current job has finished + bool terminate_early; + + // The path to the tc_scripts temporary cache + fs::path temporary_cache_path_; +}; + +class ScriptModuleDeleteMessage +{ +public: + explicit ScriptModuleDeleteMessage(ScriptModule* module) + : module_(module) { } + + void operator() (HotSwapScriptReloadMgr*) + { + module_.reset(); + } + +private: + std::unique_ptr<ScriptModule> module_; +}; + +void ScriptModule::ScheduleDelayedDelete(ScriptModule* module) +{ + sScriptReloadMgr->QueueMessage(ScriptModuleDeleteMessage(module)); +} + +/// Maps efsw actions to strings +static char const* ActionToString(efsw::Action action) +{ + switch (action) + { + case efsw::Action::Add: + return "added"; + case efsw::Action::Delete: + return "deleted"; + case efsw::Action::Moved: + return "moved"; + default: + return "modified"; + } +} + +void LibraryUpdateListener::handleFileAction(efsw::WatchID watchid, std::string const& dir, + std::string const& filename, efsw::Action action, std::string oldFilename) +{ + // TC_LOG_TRACE("scripts.hotswap", "Library listener detected change on possible module \"%s\ (%s)".", filename.c_str(), ActionToString(action)); + + // Split moved actions into a delete and an add action + if (action == efsw::Action::Moved) + { + ASSERT(!oldFilename.empty(), "Old filename doesn't exist!"); + handleFileAction(watchid, dir, oldFilename, efsw::Action::Delete); + handleFileAction(watchid, dir, filename, efsw::Action::Add); + return; + } + + sScriptReloadMgr->QueueMessage([=](HotSwapScriptReloadMgr* reloader) mutable + { + auto const path = fs::absolute( + filename, + sScriptReloadMgr->GetLibraryDirectory()); + + if (!HasValidScriptModuleName(filename)) + return; + + switch (action) + { + case efsw::Actions::Add: + TC_LOG_TRACE("scripts.hotswap", ">> Loading \"%s\" (%s)...", + path.generic_string().c_str(), ActionToString(action)); + reloader->QueueSharedLibraryChanged(path); + break; + case efsw::Actions::Delete: + TC_LOG_TRACE("scripts.hotswap", ">> Unloading \"%s\" (%s)...", + path.generic_string().c_str(), ActionToString(action)); + reloader->QueueSharedLibraryChanged(path); + break; + case efsw::Actions::Modified: + TC_LOG_TRACE("scripts.hotswap", ">> Reloading \"%s\" (%s)...", + path.generic_string().c_str(), ActionToString(action)); + reloader->QueueSharedLibraryChanged(path); + break; + default: + WPAbort(); + break; + } + }); +} + +/// Returns true when the given path has a known C++ file extension +static bool HasCXXSourceFileExtension(fs::path const& path) +{ + static std::regex const regex("^\\.(h|hpp|c|cc|cpp)$"); + return std::regex_match(path.extension().generic_string(), regex); +} + +SourceUpdateListener::SourceUpdateListener(fs::path path, std::string script_module_name) + : path_(std::move(path)), script_module_name_(std::move(script_module_name)), + watcher_id_(sScriptReloadMgr->_fileWatcher.addWatch(path_.generic_string(), this, true)) +{ + if (watcher_id_ >= 0) + { + TC_LOG_TRACE("scripts.hotswap", ">> Attached the source recompiler to \"%s\".", + path_.generic_string().c_str()); + } + else + { + TC_LOG_ERROR("scripts.hotswap", "Failed to initialize thesource recompiler on \"%s\".", + path_.generic_string().c_str()); + } +} + +SourceUpdateListener::~SourceUpdateListener() +{ + if (watcher_id_ >= 0) + { + sScriptReloadMgr->_fileWatcher.removeWatch(watcher_id_); + + TC_LOG_TRACE("scripts.hotswap", ">> Detached the source recompiler from \"%s\".", + path_.generic_string().c_str()); + } +} + +void SourceUpdateListener::handleFileAction(efsw::WatchID watchid, std::string const& dir, + std::string const& filename, efsw::Action action, std::string oldFilename) +{ + // TC_LOG_TRACE("scripts.hotswap", "Source listener detected change on possible file \"%s/%s\" (%s).", dir.c_str(), filename.c_str(), ActionToString(action)); + + // Skip the file change notification if the recompiler is disabled + if (!sWorld->getBoolConfig(CONFIG_HOTSWAP_RECOMPILER_ENABLED)) + return; + + // Split moved actions into a delete and an add action + if (action == efsw::Action::Moved) + { + ASSERT(!oldFilename.empty(), "Old filename doesn't exist!"); + handleFileAction(watchid, dir, oldFilename, efsw::Action::Delete); + handleFileAction(watchid, dir, filename, efsw::Action::Add); + return; + } + + auto const path = fs::absolute( + filename, + dir); + + // Check if the file is a C/C++ source file. + if (!path.has_extension() || !HasCXXSourceFileExtension(path)) + return; + + /// Thread safe part + sScriptReloadMgr->QueueMessage([=](HotSwapScriptReloadMgr* reloader) + { + TC_LOG_TRACE("scripts.hotswap", "Detected source change on module \"%s\", " + "queued for recompilation...", script_module_name_.c_str()); + + switch (action) + { + case efsw::Actions::Add: + TC_LOG_TRACE("scripts.hotswap", "Source file %s of module %s was added.", + path.generic_string().c_str(), script_module_name_.c_str()); + reloader->QueueAddSourceFile(script_module_name_, path); + break; + case efsw::Actions::Delete: + TC_LOG_TRACE("scripts.hotswap", "Source file %s of module %s was deleted.", + path.generic_string().c_str(), script_module_name_.c_str()); + reloader->QueueRemoveSourceFile(script_module_name_, path); + break; + case efsw::Actions::Modified: + TC_LOG_TRACE("scripts.hotswap", "Source file %s of module %s was modified.", + path.generic_string().c_str(), script_module_name_.c_str()); + reloader->QueueModifySourceFile(script_module_name_, path); + break; + default: + WPAbort(); + break; + } + }); +} + +// Returns the module reference of the given context +std::shared_ptr<ModuleReference> + ScriptReloadMgr::AcquireModuleReferenceOfContext(std::string const& context) +{ + // Return empty references for the static context exported by the worldserver + if (context == ScriptMgr::GetNameOfStaticContext()) + return { }; + + auto const itr = sScriptReloadMgr->_running_script_modules.find(context); + ASSERT(itr != sScriptReloadMgr->_running_script_modules.end() + && "Requested a reference to a non existent script context!"); + + return itr->second.first; +} + +// Returns the full hot swap implemented ScriptReloadMgr +ScriptReloadMgr* ScriptReloadMgr::instance() +{ + static HotSwapScriptReloadMgr instance; + return &instance; +} + +#endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING diff --git a/src/server/game/Scripting/ScriptReloadMgr.h b/src/server/game/Scripting/ScriptReloadMgr.h new file mode 100644 index 00000000000..f9b388f8eb0 --- /dev/null +++ b/src/server/game/Scripting/ScriptReloadMgr.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef SCRIPT_RELOADER_H +#define SCRIPT_RELOADER_H + +#include <memory> +#include <string> +#include "Define.h" +#include <boost/filesystem/path.hpp> + +/// Represents a strong reference to a dynamic library which +/// provides C++ scripts. As long as one reference to the library exists +/// the library is kept loaded in the server, which makes it possible to lazy +/// unload several script types on demand (like SpellScripts), and to +/// provide multiple versions of the same script to the script factories. +/// +/// Acquire a new reference through using: +/// `ScriptReloadMgr::AcquireModuleReferenceOfContext` +class ModuleReference +{ +public: + virtual ~ModuleReference() { } + + /// Returns the git revision hash of the referenced script module + virtual char const* GetScriptModuleRevisionHash() const = 0; + /// Returns the name of the referenced script module + virtual char const* GetScriptModule() const = 0; + /// Returns the path to the script module + virtual boost::filesystem::path const& GetModulePath() const = 0; +}; + +/// Provides the whole physical dynamic library unloading capability. +/// Loads, Reloads and Unloads dynamic libraries on changes and +/// informs the ScriptMgr about changes which were made. +/// The ScriptReloadMgr is also responsible for watching the source directory +/// and to invoke a build on changes. +class TC_GAME_API ScriptReloadMgr +{ +protected: + ScriptReloadMgr() { } + +public: + virtual ~ScriptReloadMgr() { } + + /// Initializes the ScriptReloadMgr + virtual void Initialize() { } + + /// Needs to be called periodically to check for updates on script modules. + /// Expects to be invoked in a thread safe way which means it's required that + /// the current thread is the only one which accesses the world data. + virtual void Update() { } + + /// Unloads the ScriptReloadMgr + virtual void Unload() { } + + /// Returns an owning reference to the current module of the given context + static std::shared_ptr<ModuleReference> AcquireModuleReferenceOfContext( + std::string const& context); + + /// Returns the unique ScriptReloadMgr singleton instance + static ScriptReloadMgr* instance(); +}; + +#define sScriptReloadMgr ScriptReloadMgr::instance() + +#endif // SCRIPT_RELOADER_H diff --git a/src/server/game/Scripting/ScriptSystem.cpp b/src/server/game/Scripting/ScriptSystem.cpp index e828830ec0f..52c5c1640af 100644 --- a/src/server/game/Scripting/ScriptSystem.cpp +++ b/src/server/game/Scripting/ScriptSystem.cpp @@ -21,7 +21,13 @@ #include "DatabaseEnv.h" #include "ScriptMgr.h" -ScriptPointVector const SystemMgr::_empty; +TC_GAME_API ScriptPointVector const SystemMgr::_empty; + +SystemMgr* SystemMgr::instance() +{ + static SystemMgr instance; + return &instance; +} void SystemMgr::LoadScriptWaypoints() { diff --git a/src/server/game/Scripting/ScriptSystem.h b/src/server/game/Scripting/ScriptSystem.h index 74c51e5b136..7cf8ffc85b0 100644 --- a/src/server/game/Scripting/ScriptSystem.h +++ b/src/server/game/Scripting/ScriptSystem.h @@ -45,18 +45,14 @@ struct ScriptPointMove typedef std::vector<ScriptPointMove> ScriptPointVector; -class SystemMgr +class TC_GAME_API SystemMgr { private: SystemMgr() { } ~SystemMgr() { } public: - static SystemMgr* instance() - { - static SystemMgr instance; - return &instance; - } + static SystemMgr* instance(); typedef std::unordered_map<uint32, ScriptPointVector> PointMoveMap; diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 0d30134aa9f..48ed03004ea 100644 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -1373,7 +1373,7 @@ struct OpcodeHandler void (WorldSession::*handler)(WorldPacket& recvPacket); }; -extern OpcodeHandler opcodeTable[NUM_MSG_TYPES]; +TC_GAME_API extern OpcodeHandler opcodeTable[NUM_MSG_TYPES]; #pragma pack(pop) diff --git a/src/server/game/Server/Protocol/PacketLog.cpp b/src/server/game/Server/Protocol/PacketLog.cpp index 57b76304a77..114b2ae0ecc 100644 --- a/src/server/game/Server/Protocol/PacketLog.cpp +++ b/src/server/game/Server/Protocol/PacketLog.cpp @@ -45,7 +45,7 @@ struct PacketHeader uint32 SocketPort; }; - char Direction[4]; + uint32 Direction; uint32 ConnectionId; uint32 ArrivalTicks; uint32 OptionalDataSize; @@ -69,6 +69,12 @@ PacketLog::~PacketLog() _file = NULL; } +PacketLog* PacketLog::instance() +{ + static PacketLog instance; + return &instance; +} + void PacketLog::Initialize() { std::string logsDir = sConfigMgr->GetStringDefault("LogsDir", ""); @@ -103,7 +109,7 @@ void PacketLog::LogPacket(WorldPacket const& packet, Direction direction, boost: std::lock_guard<std::mutex> lock(_logPacketLock); PacketHeader header; - *reinterpret_cast<uint32*>(header.Direction) = direction == CLIENT_TO_SERVER ? 0x47534d43 : 0x47534d53; + header.Direction = direction == CLIENT_TO_SERVER ? 0x47534d43 : 0x47534d53; header.ConnectionId = 0; header.ArrivalTicks = getMSTime(); diff --git a/src/server/game/Server/Protocol/PacketLog.h b/src/server/game/Server/Protocol/PacketLog.h index 45a3f0a4655..5e7661a884b 100644 --- a/src/server/game/Server/Protocol/PacketLog.h +++ b/src/server/game/Server/Protocol/PacketLog.h @@ -31,7 +31,7 @@ enum Direction class WorldPacket; -class PacketLog +class TC_GAME_API PacketLog { private: PacketLog(); @@ -40,11 +40,7 @@ class PacketLog std::once_flag _initializeFlag; public: - static PacketLog* instance() - { - static PacketLog instance; - return &instance; - } + static PacketLog* instance(); void Initialize(); bool CanLogPacket() const { return (_file != NULL); } diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index c380c1a5627..f65cd750ea9 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -43,6 +43,7 @@ #include "WardenWin.h" #include "MoveSpline.h" #include "WardenMac.h" +#include "Metric.h" #include <zlib.h> @@ -187,7 +188,7 @@ ObjectGuid::LowType WorldSession::GetGUIDLow() const } /// Send a packet to the client -void WorldSession::SendPacket(WorldPacket* packet) +void WorldSession::SendPacket(WorldPacket const* packet) { if (!m_Socket) return; @@ -272,119 +273,99 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) WorldPacket* packet = NULL; //! Delete packet after processing by default bool deletePacket = true; - //! To prevent infinite loop - WorldPacket* firstDelayedPacket = NULL; - //! If _recvQueue.peek() == firstDelayedPacket it means that in this Update call, we've processed all - //! *properly timed* packets, and we're now at the part of the queue where we find - //! delayed packets that were re-enqueued due to improper timing. To prevent an infinite - //! loop caused by re-enqueueing the same packets over and over again, we stop updating this session - //! and continue updating others. The re-enqueued packets will be handled in the next Update call for this session. + std::vector<WorldPacket*> requeuePackets; uint32 processedPackets = 0; time_t currentTime = time(NULL); - while (m_Socket && !_recvQueue.empty() && _recvQueue.peek(true) != firstDelayedPacket && _recvQueue.next(packet, updater)) + while (m_Socket && _recvQueue.next(packet, updater)) { - if (packet->GetOpcode() >= NUM_MSG_TYPES) + OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()]; + try { - TC_LOG_ERROR("network.opcode", "Received non-existed opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str() - , GetPlayerInfo().c_str()); - sScriptMgr->OnUnknownPacketReceive(this, *packet); - } - else - { - OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()]; - try + switch (opHandle.status) { - switch (opHandle.status) - { - case STATUS_LOGGEDIN: - if (!_player) - { - // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets - //! If player didn't log out a while ago, it means packets are being sent while the server does not recognize - //! the client to be in world yet. We will re-add the packets to the bottom of the queue and process them later. - if (!m_playerRecentlyLogout) - { - //! Prevent infinite loop - if (!firstDelayedPacket) - firstDelayedPacket = packet; - //! Because checking a bool is faster than reallocating memory - deletePacket = false; - QueuePacket(packet); - //! Log - TC_LOG_DEBUG("network", "Re-enqueueing packet with opcode %s with with status STATUS_LOGGEDIN. " - "Player is currently not in world yet.", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()); - } - } - else if (_player->IsInWorld() && AntiDOS.EvaluateOpcode(*packet, currentTime)) - { - sScriptMgr->OnPacketReceive(this, *packet); - (this->*opHandle.handler)(*packet); - LogUnprocessedTail(packet); - } - // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer - break; - case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT: - if (!_player && !m_playerRecentlyLogout && !m_playerLogout) // There's a short delay between _player = null and m_playerRecentlyLogout = true during logout - LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT", - "the player has not logged in yet and not recently logout"); - else if (AntiDOS.EvaluateOpcode(*packet, currentTime)) - { - // not expected _player or must checked in packet handler - sScriptMgr->OnPacketReceive(this, *packet); - (this->*opHandle.handler)(*packet); - LogUnprocessedTail(packet); - } - break; - case STATUS_TRANSFER: - if (!_player) - LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player has not logged in yet"); - else if (_player->IsInWorld()) - LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player is still in world"); - else if (AntiDOS.EvaluateOpcode(*packet, currentTime)) - { - sScriptMgr->OnPacketReceive(this, *packet); - (this->*opHandle.handler)(*packet); - LogUnprocessedTail(packet); - } - break; - case STATUS_AUTHED: - // prevent cheating with skip queue wait - if (m_inQueue) - { - LogUnexpectedOpcode(packet, "STATUS_AUTHED", "the player not pass queue yet"); - break; - } - - // some auth opcodes can be recieved before STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes - // however when we recieve CMSG_CHAR_ENUM we are surely no longer during the logout process. - if (packet->GetOpcode() == CMSG_CHAR_ENUM) - m_playerRecentlyLogout = false; - - if (AntiDOS.EvaluateOpcode(*packet, currentTime)) + case STATUS_LOGGEDIN: + if (!_player) + { + // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets + //! If player didn't log out a while ago, it means packets are being sent while the server does not recognize + //! the client to be in world yet. We will re-add the packets to the bottom of the queue and process them later. + if (!m_playerRecentlyLogout) { - sScriptMgr->OnPacketReceive(this, *packet); - (this->*opHandle.handler)(*packet); - LogUnprocessedTail(packet); + requeuePackets.push_back(packet); + deletePacket = false; + TC_LOG_DEBUG("network", "Re-enqueueing packet with opcode %s with with status STATUS_LOGGEDIN. " + "Player is currently not in world yet.", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()); } + } + else if (_player->IsInWorld() && AntiDOS.EvaluateOpcode(*packet, currentTime)) + { + sScriptMgr->OnPacketReceive(this, *packet); + (this->*opHandle.handler)(*packet); + LogUnprocessedTail(packet); + } + // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer + break; + case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT: + if (!_player && !m_playerRecentlyLogout && !m_playerLogout) // There's a short delay between _player = null and m_playerRecentlyLogout = true during logout + LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT", + "the player has not logged in yet and not recently logout"); + else if (AntiDOS.EvaluateOpcode(*packet, currentTime)) + { + // not expected _player or must checked in packet hanlder + sScriptMgr->OnPacketReceive(this, *packet); + (this->*opHandle.handler)(*packet); + LogUnprocessedTail(packet); + } + break; + case STATUS_TRANSFER: + if (!_player) + LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player has not logged in yet"); + else if (_player->IsInWorld()) + LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player is still in world"); + else if (AntiDOS.EvaluateOpcode(*packet, currentTime)) + { + sScriptMgr->OnPacketReceive(this, *packet); + (this->*opHandle.handler)(*packet); + LogUnprocessedTail(packet); + } + break; + case STATUS_AUTHED: + // prevent cheating with skip queue wait + if (m_inQueue) + { + LogUnexpectedOpcode(packet, "STATUS_AUTHED", "the player not pass queue yet"); break; - case STATUS_NEVER: - TC_LOG_ERROR("network.opcode", "Received not allowed opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str() - , GetPlayerInfo().c_str()); - break; - case STATUS_UNHANDLED: - TC_LOG_DEBUG("network.opcode", "Received not handled opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str() - , GetPlayerInfo().c_str()); - break; - } - } - catch (ByteBufferException const&) - { - TC_LOG_ERROR("misc", "WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.", - packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId()); - packet->hexlike(); + } + + // some auth opcodes can be recieved before STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes + // however when we recieve CMSG_CHAR_ENUM we are surely no longer during the logout process. + if (packet->GetOpcode() == CMSG_CHAR_ENUM) + m_playerRecentlyLogout = false; + + if (AntiDOS.EvaluateOpcode(*packet, currentTime)) + { + sScriptMgr->OnPacketReceive(this, *packet); + (this->*opHandle.handler)(*packet); + LogUnprocessedTail(packet); + } + break; + case STATUS_NEVER: + TC_LOG_ERROR("network.opcode", "Received not allowed opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str() + , GetPlayerInfo().c_str()); + break; + case STATUS_UNHANDLED: + TC_LOG_DEBUG("network.opcode", "Received not handled opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str() + , GetPlayerInfo().c_str()); + break; } } + catch (ByteBufferException const&) + { + TC_LOG_ERROR("network", "WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.", + packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId()); + packet->hexlike(); + } if (deletePacket) delete packet; @@ -400,6 +381,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) break; } + TC_METRIC_VALUE("processed_packets", processedPackets); + + _recvQueue.readd(requeuePackets.begin(), requeuePackets.end()); + if (m_Socket && m_Socket->IsOpen() && _warden) _warden->Update(); @@ -554,6 +539,8 @@ void WorldSession::LogoutPlayer(bool save) //! Call script hook before deletion sScriptMgr->OnPlayerLogout(_player); + TC_METRIC_EVENT("player_events", "Logout", _player->GetName()); + //! Remove the player from the world // the player may not be in the world when logging out // e.g if he got disconnected during a transfer to another map @@ -841,32 +828,15 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi) mi->RemoveMovementFlag((maskToRemove)); #endif + if (!GetPlayer()->GetVehicleBase() || !(GetPlayer()->GetVehicle()->GetVehicleInfo()->m_flags & VEHICLE_FLAG_FIXED_POSITION)) + REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT), MOVEMENTFLAG_ROOT); + /*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD. It will freeze clients that receive this player's movement info. */ - // Only adjust movement flag removal for vehicles with the VEHICLE_FLAG_FIXED_POSITION flag, or the hard coded exceptions below: - // 30236 | Argent Cannon - // 39759 | Tankbuster Cannon - if (GetPlayer()->GetVehicleBase() && ((GetPlayer()->GetVehicle()->GetVehicleInfo()->m_flags & VEHICLE_FLAG_FIXED_POSITION) || GetPlayer()->GetVehicleBase()->GetEntry() == 30236 || GetPlayer()->GetVehicleBase()->GetEntry() == 39759)) - { - // Actually players in rooted vehicles still send commands, don't clear root for these! - // Check specifically for the following conditions: - // MOVEMENTFLAG_ROOT + no other flags (0x800) - // MOVEMENTFLAG_ROOT + MOVEMENTFLAG_LEFT (0x810) - // MOVEMENTFLAG_ROOT + MOVEMENTFLAG_RIGHT (0x820) - // MOVEMENTFLAG_ROOT + MOVEMENTFLAG_PITCH_UP (0x840) - // MOVEMENTFLAG_ROOT + MOVEMENTFLAG_PITCH_DOWN (0x880) - // If none of these are true, clear the root - REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT) && mi->HasMovementFlag(MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN), - MOVEMENTFLAG_MASK_MOVING); - } - else - { - // Only remove here for non vehicles - REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT), - MOVEMENTFLAG_ROOT); - } + REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT) && mi->HasMovementFlag(MOVEMENTFLAG_MASK_MOVING), + MOVEMENTFLAG_MASK_MOVING); //! Cannot hover without SPELL_AURA_HOVER REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_HOVER) && !GetPlayer()->HasAuraType(SPELL_AURA_HOVER), @@ -892,8 +862,10 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi) REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FORWARD) && mi->HasMovementFlag(MOVEMENTFLAG_BACKWARD), MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD); - //! Cannot walk on water without SPELL_AURA_WATER_WALK - REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_WATERWALKING) && !GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK), + //! Cannot walk on water without SPELL_AURA_WATER_WALK except for ghosts + REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_WATERWALKING) && + !GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK) && + !GetPlayer()->HasAuraType(SPELL_AURA_GHOST), MOVEMENTFLAG_WATERWALKING); //! Cannot feather fall without SPELL_AURA_FEATHER_FALL @@ -1220,7 +1192,7 @@ void WorldSession::LoadPermissions() uint32 id = GetAccountId(); uint8 secLevel = GetSecurity(); - _RBACData = new rbac::RBACData(id, _accountName, realmID, secLevel); + _RBACData = new rbac::RBACData(id, _accountName, realm.Id.Realm, secLevel); _RBACData->LoadFromDB(); } @@ -1230,9 +1202,9 @@ PreparedQueryResultFuture WorldSession::LoadPermissionsAsync() uint8 secLevel = GetSecurity(); TC_LOG_DEBUG("rbac", "WorldSession::LoadPermissions [AccountId: %u, Name: %s, realmId: %d, secLevel: %u]", - id, _accountName.c_str(), realmID, secLevel); + id, _accountName.c_str(), realm.Id.Realm, secLevel); - _RBACData = new rbac::RBACData(id, _accountName, realmID, secLevel); + _RBACData = new rbac::RBACData(id, _accountName, realm.Id.Realm, secLevel); return _RBACData->LoadFromDBAsync(); } @@ -1310,7 +1282,7 @@ bool WorldSession::HasPermission(uint32 permission) bool hasPermission = _RBACData->HasPermission(permission); TC_LOG_DEBUG("rbac", "WorldSession::HasPermission [AccountId: %u, Name: %s, realmId: %d]", - _RBACData->GetId(), _RBACData->GetName().c_str(), realmID); + _RBACData->GetId(), _RBACData->GetName().c_str(), realm.Id.Realm); return hasPermission; } @@ -1318,7 +1290,7 @@ bool WorldSession::HasPermission(uint32 permission) void WorldSession::InvalidateRBACData() { TC_LOG_DEBUG("rbac", "WorldSession::Invalidaterbac::RBACData [AccountId: %u, Name: %s, realmId: %d]", - _RBACData->GetId(), _RBACData->GetName().c_str(), realmID); + _RBACData->GetId(), _RBACData->GetName().c_str(), realm.Id.Realm); delete _RBACData; _RBACData = NULL; } diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 2253b6bc684..584367bd375 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -246,7 +246,7 @@ struct PacketCounter }; /// Player session in the World -class WorldSession +class TC_GAME_API WorldSession { public: WorldSession(uint32 id, std::string&& name, std::shared_ptr<WorldSocket> sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter); @@ -264,7 +264,7 @@ class WorldSession void ReadMovementInfo(WorldPacket& data, MovementInfo* mi); void WriteMovementInfo(WorldPacket* data, MovementInfo* mi); - void SendPacket(WorldPacket* packet); + void SendPacket(WorldPacket const* packet); void SendNotification(const char *format, ...) ATTR_PRINTF(2, 3); void SendNotification(uint32 string_id, ...); void SendPetNameInvalid(uint32 error, std::string const& name, DeclinedName *declinedName); diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index a2d357cbc4d..a8a639d9b7f 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -25,6 +25,17 @@ #include <memory> +class EncryptablePacket : public WorldPacket +{ +public: + EncryptablePacket(WorldPacket const& packet, bool encrypt) : WorldPacket(packet), _encrypt(encrypt) { } + + bool NeedsEncryption() const { return _encrypt; } + +private: + bool _encrypt; +}; + using boost::asio::ip::tcp; WorldSocket::WorldSocket(tcp::socket&& socket) @@ -40,11 +51,8 @@ void WorldSocket::Start() stmt->setString(0, ip_address); stmt->setUInt32(1, inet_addr(ip_address.c_str())); - { - std::lock_guard<std::mutex> guard(_queryLock); - _queryCallback = io_service().wrap(std::bind(&WorldSocket::CheckIpCallback, this, std::placeholders::_1)); - _queryFuture = LoginDatabase.AsyncQuery(stmt); - } + _queryCallback = std::bind(&WorldSocket::CheckIpCallback, this, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); } void WorldSocket::CheckIpCallback(PreparedQueryResult result) @@ -78,17 +86,50 @@ void WorldSocket::CheckIpCallback(PreparedQueryResult result) bool WorldSocket::Update() { + EncryptablePacket* queued; + MessageBuffer buffer; + while (_bufferQueue.Dequeue(queued)) + { + ServerPktHeader header(queued->size() + 2, queued->GetOpcode()); + if (queued->NeedsEncryption()) + _authCrypt.EncryptSend(header.header, header.getHeaderLength()); + + if (buffer.GetRemainingSpace() < queued->size() + header.getHeaderLength()) + { + QueuePacket(std::move(buffer)); + buffer.Resize(4096); + } + + if (buffer.GetRemainingSpace() >= queued->size() + header.getHeaderLength()) + { + buffer.Write(header.header, header.getHeaderLength()); + if (!queued->empty()) + buffer.Write(queued->contents(), queued->size()); + } + else // single packet larger than 4096 bytes + { + MessageBuffer packetBuffer(queued->size() + header.getHeaderLength()); + packetBuffer.Write(header.header, header.getHeaderLength()); + if (!queued->empty()) + packetBuffer.Write(queued->contents(), queued->size()); + + QueuePacket(std::move(packetBuffer)); + } + + delete queued; + } + + if (buffer.GetActiveSize() > 0) + QueuePacket(std::move(buffer)); + if (!BaseSocket::Update()) return false; + if (_queryFuture.valid() && _queryFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - std::lock_guard<std::mutex> guard(_queryLock); - if (_queryFuture.valid() && _queryFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) - { - auto callback = std::move(_queryCallback); - _queryCallback = nullptr; - callback(_queryFuture.get()); - } + auto callback = _queryCallback; + _queryCallback = nullptr; + callback(_queryFuture.get()); } return true; @@ -283,9 +324,20 @@ WorldSocket::ReadDataHandlerResult WorldSocket::ReadDataHandler() switch (opcode) { case CMSG_PING: + { LogOpcodeText(opcode, sessionGuard); - return HandlePing(packet) ? ReadDataHandlerResult::Ok : ReadDataHandlerResult::Error; + try + { + return HandlePing(packet) ? ReadDataHandlerResult::Ok : ReadDataHandlerResult::Error; + } + catch (ByteBufferPositionException const&) + { + } + TC_LOG_ERROR("network", "WorldSocket::ReadDataHandler(): client %s sent malformed CMSG_PING", GetRemoteIpAddress().to_string().c_str()); + return ReadDataHandlerResult::Error; + } case CMSG_AUTH_SESSION: + { LogOpcodeText(opcode, sessionGuard); if (_authed) { @@ -295,19 +347,29 @@ WorldSocket::ReadDataHandlerResult WorldSocket::ReadDataHandler() return ReadDataHandlerResult::Error; } - HandleAuthSession(packet); - return ReadDataHandlerResult::WaitingForQuery; + try + { + HandleAuthSession(packet); + return ReadDataHandlerResult::WaitingForQuery; + } + catch (ByteBufferPositionException const&) + { + } + TC_LOG_ERROR("network", "WorldSocket::ReadDataHandler(): client %s sent malformed CMSG_AUTH_SESSION", GetRemoteIpAddress().to_string().c_str()); + return ReadDataHandlerResult::Error; + } case CMSG_KEEP_ALIVE: LogOpcodeText(opcode, sessionGuard); break; default: { sessionGuard.lock(); + LogOpcodeText(opcode, sessionGuard); + if (!_worldSession) { TC_LOG_ERROR("network.opcode", "ProcessIncoming: Client not authed opcode = %u", uint32(opcode)); - CloseSocket(); return ReadDataHandlerResult::Error; } @@ -351,29 +413,7 @@ void WorldSocket::SendPacket(WorldPacket const& packet) if (sPacketLog->CanLogPacket()) sPacketLog->LogPacket(packet, SERVER_TO_CLIENT, GetRemoteIpAddress(), GetRemotePort()); - ServerPktHeader header(packet.size() + 2, packet.GetOpcode()); - - std::unique_lock<std::mutex> guard(_writeLock); - - _authCrypt.EncryptSend(header.header, header.getHeaderLength()); - -#ifndef TC_SOCKET_USE_IOCP - if (_writeQueue.empty() && _writeBuffer.GetRemainingSpace() >= header.getHeaderLength() + packet.size()) - { - _writeBuffer.Write(header.header, header.getHeaderLength()); - if (!packet.empty()) - _writeBuffer.Write(packet.contents(), packet.size()); - } - else -#endif - { - MessageBuffer buffer(header.getHeaderLength() + packet.size()); - buffer.Write(header.header, header.getHeaderLength()); - if (!packet.empty()) - buffer.Write(packet.contents(), packet.size()); - - QueuePacket(std::move(buffer), guard); - } + _bufferQueue.Enqueue(new EncryptablePacket(packet, _authCrypt.IsInitialized())); } void WorldSocket::HandleAuthSession(WorldPacket& recvPacket) @@ -395,14 +435,11 @@ void WorldSocket::HandleAuthSession(WorldPacket& recvPacket) // Get the account information from the auth database PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME); - stmt->setInt32(0, int32(realmID)); + stmt->setInt32(0, int32(realm.Id.Realm)); stmt->setString(1, authSession->Account); - { - std::lock_guard<std::mutex> guard(_queryLock); - _queryCallback = io_service().wrap(std::bind(&WorldSocket::HandleAuthSessionCallback, this, authSession, std::placeholders::_1)); - _queryFuture = LoginDatabase.AsyncQuery(stmt); - } + _queryCallback = std::bind(&WorldSocket::HandleAuthSessionCallback, this, authSession, std::placeholders::_1); + _queryFuture = LoginDatabase.AsyncQuery(stmt); } void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<AuthSession> authSession, PreparedQueryResult result) @@ -441,10 +478,11 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<AuthSession> authSes return; } - if (authSession->RealmID != realmID) + if (authSession->RealmID != realm.Id.Realm) { SendAuthResponseError(REALM_LIST_REALM_NOT_FOUND); - TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (bad realm)."); + TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client %s requested connecting with realm id %u but this realm has id %u set in config.", + GetRemoteIpAddress().to_string().c_str(), authSession->RealmID, realm.Id.Realm); DelayedCloseSocket(); return; } @@ -559,7 +597,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<AuthSession> authSes if (wardenActive) _worldSession->InitWarden(&account.SessionKey, account.OS); - _queryCallback = io_service().wrap(std::bind(&WorldSocket::LoadSessionPermissionsCallback, this, std::placeholders::_1)); + _queryCallback = std::bind(&WorldSocket::LoadSessionPermissionsCallback, this, std::placeholders::_1); _queryFuture = _worldSession->LoadPermissionsAsync(); AsyncRead(); } diff --git a/src/server/game/Server/WorldSocket.h b/src/server/game/Server/WorldSocket.h index 9e5b35992a6..3874b60b0bb 100644 --- a/src/server/game/Server/WorldSocket.h +++ b/src/server/game/Server/WorldSocket.h @@ -26,11 +26,12 @@ #include "Util.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "MPSCQueue.h" #include <chrono> #include <boost/asio/ip/tcp.hpp> -#include <boost/asio/buffer.hpp> using boost::asio::ip::tcp; +class EncryptablePacket; #pragma pack(push, 1) @@ -47,7 +48,7 @@ struct ClientPktHeader struct AuthSession; -class WorldSocket : public Socket<WorldSocket> +class TC_GAME_API WorldSocket : public Socket<WorldSocket> { typedef Socket<WorldSocket> BaseSocket; @@ -104,8 +105,8 @@ private: MessageBuffer _headerBuffer; MessageBuffer _packetBuffer; + MPSCQueue<EncryptablePacket> _bufferQueue; - std::mutex _queryLock; PreparedQueryResultFuture _queryFuture; std::function<void(PreparedQueryResult&&)> _queryCallback; std::string _ipCountry; diff --git a/src/server/game/Server/WorldSocketMgr.cpp b/src/server/game/Server/WorldSocketMgr.cpp index 529396b3966..2faf0704d4f 100644 --- a/src/server/game/Server/WorldSocketMgr.cpp +++ b/src/server/game/Server/WorldSocketMgr.cpp @@ -24,9 +24,9 @@ #include <boost/system/error_code.hpp> -static void OnSocketAccept(tcp::socket&& sock) +static void OnSocketAccept(tcp::socket&& sock, uint32 threadIndex) { - sWorldSocketMgr.OnSocketOpen(std::forward<tcp::socket>(sock)); + sWorldSocketMgr.OnSocketOpen(std::forward<tcp::socket>(sock), threadIndex); } class WorldSocketThread : public NetworkThread<WorldSocket> @@ -47,7 +47,13 @@ WorldSocketMgr::WorldSocketMgr() : BaseSocketMgr(), _socketSendBufferSize(-1), m { } -bool WorldSocketMgr::StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port) +WorldSocketMgr& WorldSocketMgr::Instance() +{ + static WorldSocketMgr instance; + return instance; +} + +bool WorldSocketMgr::StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount) { _tcpNoDelay = sConfigMgr->GetBoolDefault("Network.TcpNodelay", true); @@ -65,9 +71,11 @@ bool WorldSocketMgr::StartNetwork(boost::asio::io_service& service, std::string return false; } - BaseSocketMgr::StartNetwork(service, bindIp, port); + BaseSocketMgr::StartNetwork(service, bindIp, port, threadCount); + + _acceptor->SetSocketFactory(std::bind(&BaseSocketMgr::GetSocketForAccept, this)); - _acceptor->AsyncAcceptManaged(&OnSocketAccept); + _acceptor->AsyncAcceptWithCallback<&OnSocketAccept>(); sScriptMgr->OnNetworkStart(); return true; @@ -80,7 +88,7 @@ void WorldSocketMgr::StopNetwork() sScriptMgr->OnNetworkStop(); } -void WorldSocketMgr::OnSocketOpen(tcp::socket&& sock) +void WorldSocketMgr::OnSocketOpen(tcp::socket&& sock, uint32 threadIndex) { // set some options here if (_socketSendBufferSize >= 0) @@ -108,7 +116,7 @@ void WorldSocketMgr::OnSocketOpen(tcp::socket&& sock) //sock->m_OutBufferSize = static_cast<size_t> (m_SockOutUBuff); - BaseSocketMgr::OnSocketOpen(std::forward<tcp::socket>(sock)); + BaseSocketMgr::OnSocketOpen(std::forward<tcp::socket>(sock), threadIndex); } NetworkThread<WorldSocket>* WorldSocketMgr::CreateThreads() const diff --git a/src/server/game/Server/WorldSocketMgr.h b/src/server/game/Server/WorldSocketMgr.h index 92a28d0c135..a5aee344bf7 100644 --- a/src/server/game/Server/WorldSocketMgr.h +++ b/src/server/game/Server/WorldSocketMgr.h @@ -30,24 +30,20 @@ class WorldSocket; /// Manages all sockets connected to peers and network threads -class WorldSocketMgr : public SocketMgr<WorldSocket> +class TC_GAME_API WorldSocketMgr : public SocketMgr<WorldSocket> { typedef SocketMgr<WorldSocket> BaseSocketMgr; public: - static WorldSocketMgr& Instance() - { - static WorldSocketMgr instance; - return instance; - } + static WorldSocketMgr& Instance(); /// Start network, listen at address:port . - bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port) override; + bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int networkThreads) override; /// Stops all network threads, It will wait for all running threads . void StopNetwork() override; - void OnSocketOpen(tcp::socket&& sock) override; + void OnSocketOpen(tcp::socket&& sock, uint32 threadIndex) override; protected: WorldSocketMgr(); diff --git a/src/server/game/Skills/SkillDiscovery.cpp b/src/server/game/Skills/SkillDiscovery.cpp index 36a7d147192..8860b391f48 100644 --- a/src/server/game/Skills/SkillDiscovery.cpp +++ b/src/server/game/Skills/SkillDiscovery.cpp @@ -88,7 +88,7 @@ void LoadSkillDiscoveryTable() { if (reportedReqSpells.find(absReqSkillOrSpell) == reportedReqSpells.end()) { - TC_LOG_ERROR("sql.sql", "Spell (ID: %u) have not existed spell (ID: %i) in `reqSpell` field in `skill_discovery_template` table", spellId, reqSkillOrSpell); + TC_LOG_ERROR("sql.sql", "Spell (ID: %u) has a non-existing spell (ID: %i) in `reqSpell` field in the `skill_discovery_template` table.", spellId, reqSkillOrSpell); reportedReqSpells.insert(absReqSkillOrSpell); } continue; @@ -101,8 +101,8 @@ void LoadSkillDiscoveryTable() { if (reportedReqSpells.find(absReqSkillOrSpell) == reportedReqSpells.end()) { - TC_LOG_ERROR("sql.sql", "Spell (ID: %u) not have MECHANIC_DISCOVERY (28) value in Mechanic field in spell.dbc" - " and not 100%% chance random discovery ability but listed for spellId %u (and maybe more) in `skill_discovery_template` table", + TC_LOG_ERROR("sql.sql", "Spell (ID: %u) does not have any MECHANIC_DISCOVERY (28) value in the Mechanic field in spell.dbc" + " nor 100%% chance random discovery ability, but is listed for spellId %u (and maybe more) in the `skill_discovery_template` table.", absReqSkillOrSpell, spellId); reportedReqSpells.insert(absReqSkillOrSpell); } @@ -117,7 +117,7 @@ void LoadSkillDiscoveryTable() if (bounds.first == bounds.second) { - TC_LOG_ERROR("sql.sql", "Spell (ID: %u) not listed in `SkillLineAbility.dbc` but listed with `reqSpell`=0 in `skill_discovery_template` table", spellId); + TC_LOG_ERROR("sql.sql", "Spell (ID: %u) is not listed in `SkillLineAbility.dbc`, but listed with `reqSpell`= 0 in the `skill_discovery_template` table.", spellId); continue; } @@ -126,7 +126,7 @@ void LoadSkillDiscoveryTable() } else { - TC_LOG_ERROR("sql.sql", "Spell (ID: %u) have negative value in `reqSpell` field in `skill_discovery_template` table", spellId); + TC_LOG_ERROR("sql.sql", "Spell (ID: %u) has a negative value in `reqSpell` field in the `skill_discovery_template` table.", spellId); continue; } @@ -135,7 +135,7 @@ void LoadSkillDiscoveryTable() while (result->NextRow()); if (!ssNonDiscoverableEntries.str().empty()) - TC_LOG_ERROR("sql.sql", "Some items can't be successfully discovered: have in chance field value < 0.000001 in `skill_discovery_template` DB table . List:\n%s", ssNonDiscoverableEntries.str().c_str()); + TC_LOG_ERROR("sql.sql", "Some items can't be successfully discovered, their chance field value is < 0.000001 in the `skill_discovery_template` DB table. List:\n%s", ssNonDiscoverableEntries.str().c_str()); // report about empty data for explicit discovery spells for (uint32 spell_id = 1; spell_id < sSpellMgr->GetSpellInfoStoreSize(); ++spell_id) @@ -149,10 +149,10 @@ void LoadSkillDiscoveryTable() continue; if (SkillDiscoveryStore.find(int32(spell_id)) == SkillDiscoveryStore.end()) - TC_LOG_ERROR("sql.sql", "Spell (ID: %u) is 100%% chance random discovery ability but not have data in `skill_discovery_template` table", spell_id); + TC_LOG_ERROR("sql.sql", "Spell (ID: %u) has got 100%% chance random discovery ability, but does not have data in the `skill_discovery_template` table.", spell_id); } - TC_LOG_INFO("server.loading", ">> Loaded %u skill discovery definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u skill discovery definitions in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } uint32 GetExplicitDiscoverySpell(uint32 spellId, Player* player) diff --git a/src/server/game/Skills/SkillDiscovery.h b/src/server/game/Skills/SkillDiscovery.h index b7fe1cdc8b2..c2020e5b075 100644 --- a/src/server/game/Skills/SkillDiscovery.h +++ b/src/server/game/Skills/SkillDiscovery.h @@ -23,8 +23,9 @@ class Player; -void LoadSkillDiscoveryTable(); -uint32 GetSkillDiscoverySpell(uint32 skillId, uint32 spellId, Player* player); -bool HasDiscoveredAllSpells(uint32 spellId, Player* player); -uint32 GetExplicitDiscoverySpell(uint32 spellId, Player* player); +TC_GAME_API void LoadSkillDiscoveryTable(); +TC_GAME_API uint32 GetSkillDiscoverySpell(uint32 skillId, uint32 spellId, Player* player); +TC_GAME_API bool HasDiscoveredAllSpells(uint32 spellId, Player* player); +TC_GAME_API uint32 GetExplicitDiscoverySpell(uint32 spellId, Player* player); + #endif diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index 5213944cc90..f76e4623137 100644 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -74,28 +74,28 @@ void LoadSkillPerfectItemTable() if (!sSpellMgr->GetSpellInfo(spellId)) { - TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has non-existent spell id in `skill_perfect_item_template`!", spellId); + TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has a non-existing spell id in the `skill_perfect_item_template`!", spellId); continue; } uint32 requiredSpecialization = fields[1].GetUInt32(); if (!sSpellMgr->GetSpellInfo(requiredSpecialization)) { - TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has non-existent required specialization spell id %u in `skill_perfect_item_template`!", spellId, requiredSpecialization); + TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has a non-existing required specialization spell id %u in the `skill_perfect_item_template`!", spellId, requiredSpecialization); continue; } float perfectCreateChance = fields[2].GetFloat(); if (perfectCreateChance <= 0.0f) { - TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has impossibly low proc chance in `skill_perfect_item_template`!", spellId); + TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u has impossibly low proc chance in the `skill_perfect_item_template`!", spellId); continue; } uint32 perfectItemType = fields[3].GetUInt32(); if (!sObjectMgr->GetItemTemplate(perfectItemType)) { - TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u references non-existent perfect item id %u in `skill_perfect_item_template`!", spellId, perfectItemType); + TC_LOG_ERROR("sql.sql", "Skill perfection data for spell %u references a non-existing perfect item id %u in the `skill_perfect_item_template`!", spellId, perfectItemType); continue; } @@ -109,7 +109,7 @@ void LoadSkillPerfectItemTable() } while (result->NextRow()); - TC_LOG_INFO("server.loading", ">> Loaded %u spell perfection definitions in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + TC_LOG_INFO("server.loading", ">> Loaded %u spell perfection definitions in %u ms.", count, GetMSTimeDiffToNow(oldMSTime)); } // struct to store information about extra item creation @@ -161,28 +161,28 @@ void LoadSkillExtraItemTable() if (!sSpellMgr->GetSpellInfo(spellId)) { - TC_LOG_ERROR("sql.sql", "Skill specialization %u has non-existent spell id in `skill_extra_item_template`!", spellId); + TC_LOG_ERROR("sql.sql", "Skill specialization %u has a non-existing spell id in the `skill_extra_item_template`!", spellId); continue; } uint32 requiredSpecialization = fields[1].GetUInt32(); if (!sSpellMgr->GetSpellInfo(requiredSpecialization)) { - TC_LOG_ERROR("sql.sql", "Skill specialization %u have not existed required specialization spell id %u in `skill_extra_item_template`!", spellId, requiredSpecialization); + TC_LOG_ERROR("sql.sql", "Skill specialization %u has a non-existing required specialization spell id %u in the `skill_extra_item_template`!", spellId, requiredSpecialization); continue; } float additionalCreateChance = fields[2].GetFloat(); if (additionalCreateChance <= 0.0f) { - TC_LOG_ERROR("sql.sql", "Skill specialization %u has too low additional create chance in `skill_extra_item_template`!", spellId); + TC_LOG_ERROR("sql.sql", "Skill specialization %u has too low additional create chance in the `skill_extra_item_template`!", spellId); continue; } uint8 additionalMaxNum = fields[3].GetUInt8(); if (!additionalMaxNum) { - TC_LOG_ERROR("sql.sql", "Skill specialization %u has 0 max number of extra items in `skill_extra_item_template`!", spellId); + TC_LOG_ERROR("sql.sql", "Skill specialization %u has 0 max number of extra items in the `skill_extra_item_template`!", spellId); continue; } diff --git a/src/server/game/Skills/SkillExtraItems.h b/src/server/game/Skills/SkillExtraItems.h index 2889b221600..5a477b65f0b 100644 --- a/src/server/game/Skills/SkillExtraItems.h +++ b/src/server/game/Skills/SkillExtraItems.h @@ -23,12 +23,14 @@ // predef classes used in functions class Player; + // returns true and sets the appropriate info if the player can create a perfect item with the given spellId -bool CanCreatePerfectItem(Player* player, uint32 spellId, float &perfectCreateChance, uint32 &perfectItemType); +TC_GAME_API bool CanCreatePerfectItem(Player* player, uint32 spellId, float &perfectCreateChance, uint32 &perfectItemType); // load perfection proc info from DB -void LoadSkillPerfectItemTable(); +TC_GAME_API void LoadSkillPerfectItemTable(); // returns true and sets the appropriate info if the player can create extra items with the given spellId -bool CanCreateExtraItems(Player* player, uint32 spellId, float &additionalChance, uint8 &additionalMax); +TC_GAME_API bool CanCreateExtraItems(Player* player, uint32 spellId, float &additionalChance, uint8 &additionalMax); // function to load the extra item creation info from DB -void LoadSkillExtraItemTable(); +TC_GAME_API void LoadSkillExtraItemTable(); + #endif diff --git a/src/server/game/Spells/Auras/SpellAuraDefines.h b/src/server/game/Spells/Auras/SpellAuraDefines.h index e0daf59fcc2..43f6b51031a 100644 --- a/src/server/game/Spells/Auras/SpellAuraDefines.h +++ b/src/server/game/Spells/Auras/SpellAuraDefines.h @@ -348,7 +348,7 @@ enum AuraType SPELL_AURA_ABILITY_PERIODIC_CRIT = 286, SPELL_AURA_DEFLECT_SPELLS = 287, SPELL_AURA_IGNORE_HIT_DIRECTION = 288, - SPELL_AURA_289 = 289, + SPELL_AURA_PREVENT_DURABILITY_LOSS = 289, SPELL_AURA_MOD_CRIT_PCT = 290, SPELL_AURA_MOD_XP_QUEST_PCT = 291, SPELL_AURA_OPEN_STABLE = 292, @@ -367,7 +367,7 @@ enum AuraType SPELL_AURA_MOD_MINIMUM_SPEED = 305, SPELL_AURA_306 = 306, SPELL_AURA_HEAL_ABSORB_TEST = 307, - SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER = 308, // NYI + SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER = 308, SPELL_AURA_309 = 309, SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE = 310, SPELL_AURA_311 = 311, diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 1cab186b95e..94fe6778ba1 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -346,7 +346,7 @@ pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= &AuraEffect::HandleNoImmediateEffect, //286 SPELL_AURA_ABILITY_PERIODIC_CRIT implemented in AuraEffect::PeriodicTick &AuraEffect::HandleNoImmediateEffect, //287 SPELL_AURA_DEFLECT_SPELLS implemented in Unit::MagicSpellHitResult and Unit::MeleeSpellHitResult &AuraEffect::HandleNoImmediateEffect, //288 SPELL_AURA_IGNORE_HIT_DIRECTION implemented in Unit::MagicSpellHitResult and Unit::MeleeSpellHitResult Unit::RollMeleeOutcomeAgainst - &AuraEffect::HandleNULL, //289 unused (3.2.0) + &AuraEffect::HandleNoImmediateEffect, //289 SPELL_AURA_PREVENT_DURABILITY_LOSS implemented in Player::DurabilityPointsLoss &AuraEffect::HandleAuraModCritPct, //290 SPELL_AURA_MOD_CRIT_PCT &AuraEffect::HandleNoImmediateEffect, //291 SPELL_AURA_MOD_XP_QUEST_PCT implemented in Player::RewardQuest &AuraEffect::HandleAuraOpenStable, //292 SPELL_AURA_OPEN_STABLE @@ -365,7 +365,7 @@ pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= &AuraEffect::HandleAuraModIncreaseSpeed, //305 SPELL_AURA_MOD_MINIMUM_SPEED &AuraEffect::HandleUnused, //306 0 spells in 3.3.5 &AuraEffect::HandleUnused, //307 0 spells in 3.3.5 - &AuraEffect::HandleNULL, //308 new aura for hunter traps + &AuraEffect::HandleNoImmediateEffect, //308 SPELL_AURA_MOD_CRIT_CHANCE_FOR_CASTER implemented in Unit::GetUnitCriticalChance and Unit::GetUnitSpellCriticalChance &AuraEffect::HandleUnused, //309 0 spells in 3.3.5 &AuraEffect::HandleNoImmediateEffect, //310 SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE implemented in Spell::CalculateDamageDone &AuraEffect::HandleNULL, //311 0 spells in 3.3.5 @@ -846,16 +846,6 @@ void AuraEffect::UpdatePeriodic(Unit* caster) case 59911: // Tenacity (vehicle) GetBase()->RefreshDuration(); break; - case 66823: case 67618: case 67619: case 67620: // Paralytic Toxin - // Get 0 effect aura - if (AuraEffect* slow = GetBase()->GetEffect(0)) - { - int32 newAmount = slow->GetAmount() - 10; - if (newAmount < -100) - newAmount = -100; - slow->ChangeAmount(newAmount); - } - break; default: break; } @@ -1325,7 +1315,7 @@ void AuraEffect::HandleModInvisibility(AuraApplication const* aurApp, uint8 mode { // apply glow vision if (target->GetTypeId() == TYPEID_PLAYER) - target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); + target->SetByteFlag(PLAYER_FIELD_BYTES2, PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); target->m_invisibility.AddFlag(type); target->m_invisibility.AddValue(type, GetAmount()); @@ -1337,7 +1327,7 @@ void AuraEffect::HandleModInvisibility(AuraApplication const* aurApp, uint8 mode // if not have different invisibility auras. // remove glow vision if (target->GetTypeId() == TYPEID_PLAYER) - target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); + target->RemoveByteFlag(PLAYER_FIELD_BYTES2, PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); target->m_invisibility.DelFlag(type); } @@ -1409,7 +1399,7 @@ void AuraEffect::HandleModStealth(AuraApplication const* aurApp, uint8 mode, boo target->SetStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) - target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH); + target->SetByteFlag(PLAYER_FIELD_BYTES2, PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION, PLAYER_FIELD_BYTE2_STEALTH); } else { @@ -1421,7 +1411,7 @@ void AuraEffect::HandleModStealth(AuraApplication const* aurApp, uint8 mode, boo target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) - target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH); + target->RemoveByteFlag(PLAYER_FIELD_BYTES2, PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION, PLAYER_FIELD_BYTE2_STEALTH); } } @@ -2400,7 +2390,7 @@ void AuraEffect::HandleAuraTrackStealthed(AuraApplication const* aurApp, uint8 m if (target->HasAuraType(GetAuraType())) return; } - target->ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply); + target->ApplyModByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_FLAGS, PLAYER_FIELD_BYTE_TRACK_STEALTHED, apply); } void AuraEffect::HandleAuraModStalked(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -2545,10 +2535,9 @@ void AuraEffect::HandleAuraAllowFlight(AuraApplication const* aurApp, uint8 mode return; } - target->SetCanFly(apply); - - if (!apply && target->GetTypeId() == TYPEID_UNIT && !target->IsLevitating()) - target->GetMotionMaster()->MoveFall(); + if (target->SetCanFly(apply)) + if (!apply && !target->IsLevitating()) + target->GetMotionMaster()->MoveFall(); } void AuraEffect::HandleAuraWaterWalk(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -2915,7 +2904,7 @@ void AuraEffect::HandleAuraModIncreaseSpeed(AuraApplication const* aurApp, uint8 Unit* target = aurApp->GetTarget(); - target->UpdateSpeed(MOVE_RUN, true); + target->UpdateSpeed(MOVE_RUN); } void AuraEffect::HandleAuraModIncreaseMountedSpeed(AuraApplication const* aurApp, uint8 mode, bool apply) const @@ -2930,7 +2919,7 @@ void AuraEffect::HandleAuraModIncreaseFlightSpeed(AuraApplication const* aurApp, Unit* target = aurApp->GetTarget(); if (mode & AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK) - target->UpdateSpeed(MOVE_FLIGHT, true); + target->UpdateSpeed(MOVE_FLIGHT); //! Update ability to fly if (GetAuraType() == SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) @@ -2938,10 +2927,9 @@ void AuraEffect::HandleAuraModIncreaseFlightSpeed(AuraApplication const* aurApp, // do not remove unit flag if there are more than this auraEffect of that kind on unit on unit if (mode & AURA_EFFECT_HANDLE_SEND_FOR_CLIENT_MASK && (apply || (!target->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) && !target->HasAuraType(SPELL_AURA_FLY)))) { - target->SetCanFly(apply); - - if (!apply && target->GetTypeId() == TYPEID_UNIT && !target->IsLevitating()) - target->GetMotionMaster()->MoveFall(); + if (target->SetCanFly(apply)) + if (!apply && !target->IsLevitating()) + target->GetMotionMaster()->MoveFall(); } //! Someone should clean up these hacks and remove it from this function. It doesn't even belong here. @@ -2965,7 +2953,7 @@ void AuraEffect::HandleAuraModIncreaseSwimSpeed(AuraApplication const* aurApp, u Unit* target = aurApp->GetTarget(); - target->UpdateSpeed(MOVE_SWIM, true); + target->UpdateSpeed(MOVE_SWIM); } void AuraEffect::HandleAuraModDecreaseSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const @@ -2975,12 +2963,12 @@ void AuraEffect::HandleAuraModDecreaseSpeed(AuraApplication const* aurApp, uint8 Unit* target = aurApp->GetTarget(); - target->UpdateSpeed(MOVE_RUN, true); - target->UpdateSpeed(MOVE_SWIM, true); - target->UpdateSpeed(MOVE_FLIGHT, true); - target->UpdateSpeed(MOVE_RUN_BACK, true); - target->UpdateSpeed(MOVE_SWIM_BACK, true); - target->UpdateSpeed(MOVE_FLIGHT_BACK, true); + target->UpdateSpeed(MOVE_RUN); + target->UpdateSpeed(MOVE_SWIM); + target->UpdateSpeed(MOVE_FLIGHT); + target->UpdateSpeed(MOVE_RUN_BACK); + target->UpdateSpeed(MOVE_SWIM_BACK); + target->UpdateSpeed(MOVE_FLIGHT_BACK); } void AuraEffect::HandleAuraModUseNormalSpeed(AuraApplication const* aurApp, uint8 mode, bool /*apply*/) const @@ -2990,9 +2978,9 @@ void AuraEffect::HandleAuraModUseNormalSpeed(AuraApplication const* aurApp, uint Unit* target = aurApp->GetTarget(); - target->UpdateSpeed(MOVE_RUN, true); - target->UpdateSpeed(MOVE_SWIM, true); - target->UpdateSpeed(MOVE_FLIGHT, true); + target->UpdateSpeed(MOVE_RUN); + target->UpdateSpeed(MOVE_SWIM); + target->UpdateSpeed(MOVE_FLIGHT); } /*********************************************************/ @@ -3384,7 +3372,7 @@ void AuraEffect::HandleAuraModSchoolImmunity(AuraApplication const* aurApp, uint && !iter->second->IsPositive() //Don't remove positive spells && spell->Id != GetId()) //Don't remove self { - target->RemoveAura(iter, AURA_REMOVE_BY_ENEMY_SPELL); + target->RemoveAura(iter); } else ++iter; @@ -4686,7 +4674,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool case 71563: if (Aura* newAura = target->AddAura(71564, target)) newAura->SetStackAmount(newAura->GetSpellInfo()->StackAmount); - break; + break; } } // AT REMOVE @@ -4808,7 +4796,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool uint32 spellId = 24659; if (apply && caster) { - SpellInfo const* spell = sSpellMgr->EnsureSpellInfo(spellId); + SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); @@ -4823,7 +4811,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool uint32 spellId = 24662; if (apply && caster) { - SpellInfo const* spell = sSpellMgr->EnsureSpellInfo(spellId); + SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); break; @@ -5248,7 +5236,7 @@ void AuraEffect::HandleAuraOverrideSpells(AuraApplication const* aurApp, uint8 m if (apply) { - target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, overrideId); + target->SetUInt16Value(PLAYER_FIELD_BYTES2, PLAYER_BYTES_2_OVERRIDE_SPELLS_UINT16_OFFSET, overrideId); if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId)) for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i) if (uint32 spellId = overrideSpells->spellId[i]) @@ -5256,7 +5244,7 @@ void AuraEffect::HandleAuraOverrideSpells(AuraApplication const* aurApp, uint8 m } else { - target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, 0); + target->SetUInt16Value(PLAYER_FIELD_BYTES2, PLAYER_BYTES_2_OVERRIDE_SPELLS_UINT16_OFFSET, 0); if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId)) for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i) if (uint32 spellId = overrideSpells->spellId[i]) @@ -5302,9 +5290,9 @@ void AuraEffect::HandlePreventResurrection(AuraApplication const* aurApp, uint8 return; if (apply) - aurApp->GetTarget()->RemoveByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER); + aurApp->GetTarget()->RemoveByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_FLAGS, PLAYER_FIELD_BYTE_RELEASE_TIMER); else if (!aurApp->GetTarget()->GetBaseMap()->Instanceable()) - aurApp->GetTarget()->SetByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER); + aurApp->GetTarget()->SetByteFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTES_OFFSET_FLAGS, PLAYER_FIELD_BYTE_RELEASE_TIMER); } void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const @@ -5974,9 +5962,6 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c caster->CalcAbsorbResist(target, GetSpellInfo()->GetSchoolMask(), DOT, damage, &absorb, &resist, m_spellInfo); - if (target->GetHealth() < damage) - damage = uint32(target->GetHealth()); - TC_LOG_DEBUG("spells.periodic", "PeriodicTick: %s health leech of %s for %u dmg inflicted by %u abs is %u", GetCasterGUID().ToString().c_str(), target->GetGUID().ToString().c_str(), damage, GetId(), absorb); diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.h b/src/server/game/Spells/Auras/SpellAuraEffects.h index b400520a08a..32a7b97fff2 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.h +++ b/src/server/game/Spells/Auras/SpellAuraEffects.h @@ -27,7 +27,7 @@ class Aura; typedef void(AuraEffect::*pAuraEffectHandler)(AuraApplication const* aurApp, uint8 mode, bool apply) const; -class AuraEffect +class TC_GAME_API AuraEffect { friend void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount); friend Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32* baseAmount, Item* castItem, ObjectGuid casterGUID); diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index 1ca5df6b327..35606989240 100644 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -337,7 +337,8 @@ m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID( m_castItemGuid(castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_applyTime(time(NULL)), 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_dropEvent(nullptr) +m_isRemoved(false), m_isSingleTarget(false), m_isUsingCharges(false), m_dropEvent(nullptr), +m_procCooldown(std::chrono::steady_clock::time_point::min()) { if (m_spellInfo->ManaPerSecond || m_spellInfo->ManaPerSecondPerLevel) m_timeCla = 1 * IN_MILLISECONDS; @@ -469,7 +470,7 @@ void Aura::_Remove(AuraRemoveMode removeMode) if (m_dropEvent) { - m_dropEvent->to_Abort = true; + m_dropEvent->ScheduleAbort(); m_dropEvent = nullptr; } } @@ -789,7 +790,7 @@ uint8 Aura::CalcMaxCharges(Unit* caster) const { uint32 maxProcCharges = m_spellInfo->ProcCharges; if (SpellProcEntry const* procEntry = sSpellMgr->GetSpellProcEntry(GetId())) - maxProcCharges = procEntry->charges; + maxProcCharges = procEntry->Charges; if (caster) if (Player* modOwner = caster->GetSpellModOwner()) @@ -1851,22 +1852,17 @@ bool Aura::CanStackWith(Aura const* existingAura) const return true; } -bool Aura::IsProcOnCooldown() const +bool Aura::IsProcOnCooldown(std::chrono::steady_clock::time_point now) const { - /*if (m_procCooldown) - { - if (m_procCooldown > time(NULL)) - return true; - }*/ - return false; + return m_procCooldown > now; } -void Aura::AddProcCooldown(uint32 /*msec*/) +void Aura::AddProcCooldown(std::chrono::steady_clock::time_point cooldownEnd) { - //m_procCooldown = time(NULL) + msec; + m_procCooldown = cooldownEnd; } -void Aura::PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo) +void Aura::PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo, std::chrono::steady_clock::time_point now) { bool prepare = CallScriptPrepareProcHandlers(aurApp, eventInfo); if (!prepare) @@ -1884,10 +1880,10 @@ void Aura::PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInf ASSERT(procEntry); // cooldowns should be added to the whole aura (see 51698 area aura) - AddProcCooldown(procEntry->cooldown); + AddProcCooldown(now + procEntry->Cooldown); } -bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo) const +bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo, std::chrono::steady_clock::time_point now) const { SpellProcEntry const* procEntry = sSpellMgr->GetSpellProcEntry(GetId()); // only auras with spell proc entry can trigger proc @@ -1899,7 +1895,7 @@ bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventI return false; // check proc cooldown - if (IsProcOnCooldown()) + if (IsProcOnCooldown(now)) return false; /// @todo @@ -1963,16 +1959,16 @@ bool Aura::IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventI float Aura::CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const { - float chance = procEntry.chance; + float chance = procEntry.Chance; // calculate chances depending on unit with caster's data // so talents modifying chances and judgements will have properly calculated proc chance if (Unit* caster = GetCaster()) { // calculate ppm chance if present and we're using weapon - if (eventInfo.GetDamageInfo() && procEntry.ratePerMinute != 0) + if (eventInfo.GetDamageInfo() && procEntry.ProcsPerMinute != 0) { uint32 WeaponSpeed = caster->GetAttackTime(eventInfo.GetDamageInfo()->GetAttackType()); - chance = caster->GetPPMProcChance(WeaponSpeed, procEntry.ratePerMinute, GetSpellInfo()); + chance = caster->GetPPMProcChance(WeaponSpeed, procEntry.ProcsPerMinute, GetSpellInfo()); } // apply chance modifer aura, applies also to ppm chance (see improved judgement of light spell) if (Player* modOwner = caster->GetSpellModOwner()) diff --git a/src/server/game/Spells/Auras/SpellAuras.h b/src/server/game/Spells/Auras/SpellAuras.h index 2180f524194..a147957f258 100644 --- a/src/server/game/Spells/Auras/SpellAuras.h +++ b/src/server/game/Spells/Auras/SpellAuras.h @@ -39,7 +39,7 @@ class ChargeDropEvent; // update aura target map every 500 ms instead of every update - reduce amount of grid searcher calls #define UPDATE_TARGET_MAP_INTERVAL 500 -class AuraApplication +class TC_GAME_API AuraApplication { friend void Unit::_ApplyAura(AuraApplication * aurApp, uint8 effMask); friend void Unit::_UnapplyAura(AuraApplicationMap::iterator &i, AuraRemoveMode removeMode); @@ -82,7 +82,7 @@ class AuraApplication void ClientUpdate(bool remove = false); }; -class Aura +class TC_GAME_API Aura { friend Aura* Unit::_TryStackingOrRefreshingExistingAura(SpellInfo const* newAura, uint8 effMask, Unit* caster, int32 *baseAmount, Item* castItem, ObjectGuid casterGUID); public: @@ -203,12 +203,12 @@ class Aura // this subsystem is not yet in use - the core of it is functional, but still some research has to be done // and some dependant problems fixed before it can replace old proc system (for example cooldown handling) // currently proc system functionality is implemented in Unit::ProcDamageAndSpell - bool IsProcOnCooldown() const; - void AddProcCooldown(uint32 msec); + bool IsProcOnCooldown(std::chrono::steady_clock::time_point now) const; + void AddProcCooldown(std::chrono::steady_clock::time_point cooldownEnd); bool IsUsingCharges() const { return m_isUsingCharges; } void SetUsingCharges(bool val) { m_isUsingCharges = val; } - void PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo); - bool IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo) const; + void PrepareProcToTrigger(AuraApplication* aurApp, ProcEventInfo& eventInfo, std::chrono::steady_clock::time_point now); + bool IsProcTriggeredOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo, std::chrono::steady_clock::time_point now) const; float CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const; void TriggerProcOnEvent(AuraApplication* aurApp, ProcEventInfo& eventInfo); @@ -269,11 +269,13 @@ class Aura ChargeDropEvent* m_dropEvent; + std::chrono::steady_clock::time_point m_procCooldown; + private: Unit::AuraApplicationList m_removedApplications; }; -class UnitAura : public Aura +class TC_GAME_API UnitAura : public Aura { friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, ObjectGuid casterGUID); protected: @@ -294,7 +296,7 @@ class UnitAura : public Aura DiminishingGroup m_AuraDRGroup:8; // Diminishing }; -class DynObjAura : public Aura +class TC_GAME_API DynObjAura : public Aura { friend Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owner, Unit* caster, int32 *baseAmount, Item* castItem, ObjectGuid casterGUID); protected: @@ -305,12 +307,12 @@ class DynObjAura : public Aura void FillTargetMap(std::map<Unit*, uint8> & targets, Unit* caster) override; }; -class ChargeDropEvent : public BasicEvent +class TC_GAME_API ChargeDropEvent : public BasicEvent { friend class Aura; protected: ChargeDropEvent(Aura* base, AuraRemoveMode mode) : _base(base), _mode(mode) { } - bool Execute(uint64 /*e_time*/, uint32 /*p_time*/); + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override; private: Aura* _base; diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 23e2f144ff2..5e58a602a43 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -602,7 +602,7 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO //Auto Shot & Shoot (wand) m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell(); - + m_isDelayedInstantCast = false; m_runesState = 0; @@ -979,14 +979,22 @@ void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTa { CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (target) - m_targets.SetDst(*target); + { + SpellDestination dest(*target); + CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); + m_targets.SetDst(dest); + } } else TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex); break; case TARGET_DEST_CHANNEL_CASTER: - m_targets.SetDst(*channeledSpell->GetCaster()); + { + SpellDestination dest(*channeledSpell->GetCaster()); + CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); + m_targets.SetDst(dest); break; + } default: ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type"); break; @@ -1042,7 +1050,11 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar if (m_spellInfo->RequiresSpellFocus) { if (focusObject) - m_targets.SetDst(*focusObject); + { + SpellDestination dest(*focusObject); + CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); + m_targets.SetDst(dest); + } return; } break; @@ -1068,7 +1080,6 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_UNIT: - { if (Unit* unit = target->ToUnit()) AddUnitTarget(unit, effMask, true, false); else @@ -1077,7 +1088,6 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar return; } break; - } case TARGET_OBJECT_TYPE_GOBJ: if (GameObject* gobjTarget = target->ToGameObject()) AddGOTarget(gobjTarget, effMask); @@ -1088,8 +1098,12 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar } break; case TARGET_OBJECT_TYPE_DEST: - m_targets.SetDst(*target); + { + SpellDestination dest(*target); + CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); + m_targets.SetDst(dest); break; + } default: ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type"); break; @@ -1288,18 +1302,30 @@ void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplici } default: { - float dist; + float dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); float angle = targetType.CalcDirectionAngle(); float objSize = m_caster->GetObjectSize(); - if (targetType.GetTarget() == TARGET_DEST_CASTER_SUMMON) - dist = PET_FOLLOW_DIST; - else - dist = m_spellInfo->Effects[effIndex].CalcRadius(m_caster); if (dist < objSize) dist = objSize; - else if (targetType.GetTarget() == TARGET_DEST_CASTER_RANDOM) - dist = objSize + (dist - objSize) * float(rand_norm()); + + switch (targetType.GetTarget()) + { + case TARGET_DEST_CASTER_SUMMON: + dist = PET_FOLLOW_DIST; + break; + case TARGET_DEST_CASTER_RANDOM: + dist = objSize + (dist - objSize) * float(rand_norm()); + break; + case TARGET_DEST_CASTER_FRONT_LEFT: + case TARGET_DEST_CASTER_BACK_LEFT: + case TARGET_DEST_CASTER_FRONT_RIGHT: + case TARGET_DEST_CASTER_BACK_RIGHT: + dist = dist + objSize; + break; + default: + break; + } Position pos = dest._position; m_caster->MovePositionToFirstCollision(pos, dist, angle); @@ -1538,7 +1564,7 @@ void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex) if (Creature* creatureTarget = unit->ToCreature()) { - if (!(creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_PROJECTILE_COLLISION)) + if (!(creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_COLLIDE_WITH_MISSILES)) continue; } } @@ -2294,8 +2320,14 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) } } + bool enablePvP = false; // need to check PvP state before spell effects, but act on it afterwards + if (spellHitTarget) { + // if target is flagged for pvp also flag caster if a player + if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) + enablePvP = true; // Decide on PvP flagging now, but act on it later. + SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura); if (missInfo2 != SPELL_MISS_NONE) { @@ -2435,6 +2467,10 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) unit->SetStandState(UNIT_STAND_STATE_STAND); } + // Check for SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER + if (m_spellInfo->HasAttribute(SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER) && unit->GetTypeId() != TYPEID_PLAYER) + caster->CastSpell(unit, SPELL_INTERRUPT_NONPLAYER, true); + if (spellHitTarget) { //AI functions @@ -2448,8 +2484,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // Needs to be called after dealing damage/healing to not remove breaking on damage auras DoTriggersOnSpellHit(spellHitTarget, mask); - // if target is fallged for pvp also flag caster if a player - if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) + if (enablePvP) m_caster->ToPlayer()->UpdatePvP(true); CallScriptAfterHitHandlers(); @@ -2884,7 +2919,7 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); - // Fill cost data (not use power for item casts + // Fill cost data (do not use power for item casts) m_powerCost = m_CastItem ? 0 : m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); @@ -2960,12 +2995,17 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered } // don't allow channeled spells / spells with cast time to be cast while moving + // exception are only channeled spells that have no casttime and SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING // (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in) - if ((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->isMoving() && m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) + if ((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && !(m_caster->IsCharmed() && m_caster->GetCharmerGUID().IsCreature()) && m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT)) { - SendCastResult(SPELL_FAILED_MOVING); - finish(false); - return; + // 1. Is a channel spell, 2. Has no casttime, 3. And has flag to allow movement during channel + if (!(m_spellInfo->IsChanneled() && !m_casttime && m_spellInfo->HasAttribute(SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING))) + { + SendCastResult(SPELL_FAILED_MOVING); + finish(false); + return; + } } // set timer base at cast time @@ -3193,6 +3233,10 @@ void Spell::cast(bool skipCheck) return; } + if (m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) + if (Creature* pet = ObjectAccessor::GetCreature(*m_caster, m_caster->GetPetGUID())) + pet->DespawnOrUnsummon(); + PrepareTriggersExecutedOnHit(); CallScriptOnCastHandlers(); @@ -3502,12 +3546,18 @@ void Spell::update(uint32 difftime) // check if the player caster has moved before the spell finished if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) && - m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && - (m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR))) + m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT && + (m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR)))) { // don't cancel for melee, autorepeat, triggered and instant spells - if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered()) - cancel(); + if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered() && !(IsChannelActive() && m_spellInfo->HasAttribute(SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING))) + { + // if charmed by creature, trust the AI not to cheat and allow the cast to proceed + // @todo this is a hack, "creature" movesplines don't differentiate turning/moving right now + // however, checking what type of movement the spline is for every single spline would be really expensive + if (!m_caster->GetCharmerGUID().IsCreature()) + cancel(); + } } switch (m_spellState) @@ -3773,6 +3823,9 @@ void Spell::SendCastResult(SpellCastResult result) if (m_caster->ToPlayer()->GetSession()->PlayerLoading()) // don't send cast results at loading time return; + if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) + result = SPELL_FAILED_DONT_REPORT; + SendCastResult(m_caster->ToPlayer(), m_spellInfo, m_cast_count, result, m_customError); } @@ -3789,6 +3842,9 @@ void Spell::SendPetCastResult(SpellCastResult result) if (!player) return; + if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) + result = SPELL_FAILED_DONT_REPORT; + WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1); WriteCastResultInfo(data, player, m_spellInfo, m_cast_count, result, m_customError); @@ -3808,10 +3864,10 @@ void Spell::SendSpellStart() if (schoolImmunityMask || mechanicImmunityMask) castFlags |= CAST_FLAG_IMMUNITY; - if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) + if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_cast_count) castFlags |= CAST_FLAG_PENDING; - if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO)) + if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA)) castFlags |= CAST_FLAG_AMMO; if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) @@ -3861,10 +3917,10 @@ void Spell::SendSpellGo() uint32 castFlags = CAST_FLAG_UNKNOWN_9; // triggered spells with spell visual != 0 - if ((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) + if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_cast_count) castFlags |= CAST_FLAG_PENDING; - if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO)) + if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA)) castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual if ((m_caster->GetTypeId() == TYPEID_PLAYER || @@ -4803,7 +4859,7 @@ SpellCastResult Spell::CheckCast(bool strict) // cancel autorepeat spells if cast start when moving // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code) - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving()) + if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() && (!m_caster->IsCharmed() || !m_caster->GetCharmerGUID().IsCreature())) { // skip stuck spell to allow use it in falling case and apply spell limitations at movement if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR) || m_spellInfo->Effects[0].Effect != SPELL_EFFECT_STUCK) && @@ -4831,6 +4887,7 @@ SpellCastResult Spell::CheckCast(bool strict) m_customError = SpellCustomErrors(condInfo.mLastFailedCondition->ErrorTextId); return SpellCastResult(condInfo.mLastFailedCondition->ErrorType); } + if (!condInfo.mLastFailedCondition || !condInfo.mLastFailedCondition->ConditionTarget) return SPELL_FAILED_CASTER_AURASTATE; return SPELL_FAILED_BAD_TARGETS; @@ -5140,7 +5197,11 @@ SpellCastResult Spell::CheckCast(bool strict) return SPELL_FAILED_OUT_OF_RANGE; else if (!result || m_preGeneratedPath.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) return SPELL_FAILED_NOPATH; + else if (m_preGeneratedPath.IsInvalidDestinationZ(target)) // Check position z, if not in a straight line + return SPELL_FAILED_NOPATH; } + else if (m_preGeneratedPath.IsInvalidDestinationZ(target)) // Check position z, if in a straight line + return SPELL_FAILED_NOPATH; m_preGeneratedPath.ReducePathLenghtByDist(objSize); // move back } @@ -5256,7 +5317,7 @@ SpellCastResult Spell::CheckCast(bool strict) switch (SummonProperties->Category) { case SUMMON_CATEGORY_PET: - if (m_caster->GetPetGUID()) + if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; // intentional missing break, check both GetPetGUID() and GetCharmGUID for SUMMON_CATEGORY_PET case SUMMON_CATEGORY_PUPPET: @@ -5272,7 +5333,7 @@ SpellCastResult Spell::CheckCast(bool strict) { if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; - if (m_targets.GetUnitTarget()->GetPetGUID()) + if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && m_targets.GetUnitTarget()->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } break; @@ -5281,13 +5342,13 @@ SpellCastResult Spell::CheckCast(bool strict) { if (m_caster->GetPetGUID()) //let warlock do a replacement summon { - if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK) + if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = m_caster->ToPlayer()->GetPet()) pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID()); } - else + else if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } @@ -5306,6 +5367,9 @@ SpellCastResult Spell::CheckCast(bool strict) if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell return SPELL_FAILED_BAD_TARGETS; + if (target->HasSummonPending()) + return SPELL_FAILED_SUMMON_PENDING; + // check if our map is dungeon MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); if (map->IsDungeon()) @@ -5411,7 +5475,7 @@ SpellCastResult Spell::CheckCast(bool strict) if (m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_CHARM || m_spellInfo->Effects[i].ApplyAuraName == SPELL_AURA_MOD_POSSESS) { - if (m_caster->GetPetGUID()) + if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (m_caster->GetCharmGUID()) @@ -5441,7 +5505,7 @@ SpellCastResult Spell::CheckCast(bool strict) } case SPELL_AURA_MOUNTED: { - if (m_caster->IsInWater()) + if (m_caster->IsInWater() && m_spellInfo->HasAura(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED)) return SPELL_FAILED_ONLY_ABOVEWATER; // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells @@ -5478,7 +5542,7 @@ SpellCastResult Spell::CheckCast(bool strict) Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId()); if (AreaTableEntry const* area = sAreaTableStore.LookupEntry(m_originalCaster->GetAreaId())) if (area->flags & AREA_FLAG_NO_FLY_ZONE || (Bf && !Bf->CanFlyIn())) - return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE; + return SPELL_FAILED_NOT_HERE; } break; } @@ -5557,7 +5621,14 @@ SpellCastResult Spell::CheckPetCast(Unit* target) m_targets.SetUnitTarget(target); } - // cooldown + // check power requirement + // this would be zero until ::prepare normally, we set it here (it gets reset in ::prepare) + m_powerCost = m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask); + SpellCastResult failReason = CheckPower(); + if (failReason != SPELL_CAST_OK) + return failReason; + + // check cooldown if (Creature* creatureCaster = m_caster->ToCreature()) if (!creatureCaster->GetSpellHistory()->IsReady(m_spellInfo)) return SPELL_FAILED_NOT_READY; @@ -5700,42 +5771,58 @@ SpellCastResult Spell::CheckCasterAuras() const bool Spell::CanAutoCast(Unit* target) { + if (!target) + return (CheckPetCast(target) == SPELL_CAST_OK); + ObjectGuid targetguid = target->GetGUID(); - for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) + // check if target already has the same or a more powerful aura + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { - if (m_spellInfo->Effects[j].Effect == SPELL_EFFECT_APPLY_AURA) + if (!GetSpellInfo()->Effects[i].IsAura()) + continue; + + AuraType const& auraType = AuraType(GetSpellInfo()->Effects[i].ApplyAuraName); + Unit::AuraEffectList const& auras = target->GetAuraEffectsByType(auraType); + for (Unit::AuraEffectList::const_iterator auraIt = auras.begin(); auraIt != auras.end(); ++auraIt) { - if (m_spellInfo->StackAmount <= 1) + if (GetSpellInfo()->Id == (*auraIt)->GetSpellInfo()->Id) + return false; + + switch (sSpellMgr->CheckSpellGroupStackRules(GetSpellInfo(), (*auraIt)->GetSpellInfo())) { - if (target->HasAuraEffect(m_spellInfo->Id, j)) + case SPELL_GROUP_STACK_RULE_EXCLUSIVE: return false; - } - else - { - if (AuraEffect* aureff = target->GetAuraEffect(m_spellInfo->Id, j)) - if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount) + case SPELL_GROUP_STACK_RULE_EXCLUSIVE_FROM_SAME_CASTER: + if (GetCaster() == (*auraIt)->GetCaster()) return false; + break; + case SPELL_GROUP_STACK_RULE_EXCLUSIVE_SAME_EFFECT: // this one has further checks, but i don't think they're necessary for autocast logic + case SPELL_GROUP_STACK_RULE_EXCLUSIVE_HIGHEST: + if (abs(GetSpellInfo()->Effects[i].BasePoints) <= abs((*auraIt)->GetAmount())) + return false; + break; + case SPELL_GROUP_STACK_RULE_DEFAULT: + default: + break; } } - else if (m_spellInfo->Effects[j].IsAreaAuraEffect()) - { - if (target->HasAuraEffect(m_spellInfo->Id, j)) - return false; - } } SpellCastResult result = CheckPetCast(target); - if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT) { + // do not check targets for ground-targeted spells (we target them on top of the intended target anyway) + if (GetSpellInfo()->ExplicitTargetMask & TARGET_FLAG_DEST_LOCATION) + return true; SelectSpellTargets(); //check if among target units, our WANTED target is as well (->only self cast spells return false) - for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetguid) return true; } - return false; //target invalid + // either the cast failed or the intended target wouldn't be hit + return false; } SpellCastResult Spell::CheckRange(bool strict) @@ -5744,55 +5831,88 @@ SpellCastResult Spell::CheckRange(bool strict) if (!strict && m_casttime == 0) return SPELL_CAST_OK; - uint32 range_type = 0; + Unit* target = m_targets.GetUnitTarget(); + float minRange = 0.0f; + float maxRange = 0.0f; + float rangeMod = 0.0f; + if (strict && IsNextMeleeSwingSpell()) + maxRange = 100.0f; + else if (m_spellInfo->RangeEntry) + { + if (m_spellInfo->RangeEntry->type & SPELL_RANGE_MELEE) + { + rangeMod = m_caster->GetCombatReach() + 4.0f / 3.0f; + if (target) + rangeMod += target->GetCombatReach(); + else + rangeMod += m_caster->GetCombatReach(); - if (m_spellInfo->RangeEntry) - { - // check needed by 68766 51693 - both spells are cast on enemies and have 0 max range - // these are triggered by other spells - possibly we should omit range check in that case? - if (m_spellInfo->RangeEntry->ID == 1) - return SPELL_CAST_OK; + rangeMod = std::max(rangeMod, NOMINAL_MELEE_RANGE); + } + else + { + float meleeRange = 0.0f; + if (m_spellInfo->RangeEntry->type & SPELL_RANGE_RANGED) + { + meleeRange = m_caster->GetCombatReach() + 4.0f / 3.0f; + if (target) + meleeRange += target->GetCombatReach(); + else + meleeRange += m_caster->GetCombatReach(); + + meleeRange = std::max(meleeRange, NOMINAL_MELEE_RANGE); + } - range_type = m_spellInfo->RangeEntry->type; + minRange = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo) + meleeRange; + maxRange = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo); + + if (target || m_targets.GetCorpseTarget()) + { + rangeMod = m_caster->GetCombatReach(); + if (target) + rangeMod += target->GetCombatReach(); + + if (minRange > 0.0f && !(m_spellInfo->RangeEntry->type & SPELL_RANGE_RANGED)) + minRange += rangeMod; + } + } + + if (target && m_caster->isMoving() && target->isMoving() && !m_caster->IsWalking() && !target->IsWalking() && + (m_spellInfo->RangeEntry->type & SPELL_RANGE_MELEE || target->GetTypeId() == TYPEID_PLAYER)) + rangeMod += 5.0f / 3.0f; } - Unit* target = m_targets.GetUnitTarget(); - float max_range = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo); - float min_range = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo); + if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) && m_caster->GetTypeId() == TYPEID_PLAYER) + if (Item* ranged = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK, true)) + maxRange *= ranged->GetTemplate()->RangedModRange * 0.01f; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, maxRange, this); + + maxRange += rangeMod; + + minRange *= minRange; + maxRange *= maxRange; if (target && target != m_caster) { - if (range_type == SPELL_RANGE_MELEE) - { - // Because of lag, we can not check too strictly here. - if (!m_caster->IsWithinMeleeRange(target, max_range)) - return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; - } - else if (!m_caster->IsWithinCombatRange(target, max_range)) - return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; //0x5A; + if (m_caster->GetExactDistSq(target) > maxRange) + return SPELL_FAILED_OUT_OF_RANGE; - if (range_type == SPELL_RANGE_RANGED) - { - if (m_caster->IsWithinMeleeRange(target)) - return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; - } - else if (min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0 - return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; + if (minRange > 0.0f && m_caster->GetExactDistSq(target) < minRange) + return SPELL_FAILED_OUT_OF_RANGE; if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target)) - return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_UNIT_NOT_INFRONT : SPELL_FAILED_DONT_REPORT; + return SPELL_FAILED_UNIT_NOT_INFRONT; } if (m_targets.HasDst() && !m_targets.HasTraj()) { - if (!m_caster->IsWithinDist3d(m_targets.GetDstPos(), max_range)) - return SPELL_FAILED_OUT_OF_RANGE; - if (min_range && m_caster->IsWithinDist3d(m_targets.GetDstPos(), min_range)) - return SPELL_FAILED_TOO_CLOSE; + if (m_caster->GetExactDistSq(m_targets.GetDstPos()) > maxRange) + return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; + if (minRange > 0.0f && m_caster->GetExactDistSq(m_targets.GetDstPos()) < minRange) + return !(_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; } return SPELL_CAST_OK; @@ -6317,11 +6437,11 @@ SpellCastResult Spell::CheckItems() // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) - return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; + return SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) - return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; + return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // offhand hand weapon required @@ -6331,11 +6451,11 @@ SpellCastResult Spell::CheckItems() // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) - return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; + return SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) - return (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; + return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } } @@ -6882,7 +7002,7 @@ SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& sk reqSkillValue = lockInfo->Skill[j]; // castitem check: rogue using skeleton keys. the skill values should not be added in this case. - skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ? + skillValue = m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER ? 0 : m_caster->ToPlayer()->GetSkillValue(skillId); // skill bonus provided by casting spell (mostly item spells) diff --git a/src/server/game/Spells/Spell.h b/src/server/game/Spells/Spell.h index 696d2801645..46384fc54ec 100644 --- a/src/server/game/Spells/Spell.h +++ b/src/server/game/Spells/Spell.h @@ -80,7 +80,7 @@ enum SpellRangeFlag SPELL_RANGE_RANGED = 2 //hunter range and ranged weapon }; -struct SpellDestination +struct TC_GAME_API SpellDestination { SpellDestination(); SpellDestination(float x, float y, float z, float orientation = 0.0f, uint32 mapId = MAPID_INVALID); @@ -95,7 +95,7 @@ struct SpellDestination Position _transportOffset; }; -class SpellCastTargets +class TC_GAME_API SpellCastTargets { public: SpellCastTargets(); @@ -218,7 +218,9 @@ enum SpellEffectHandleMode typedef std::list<std::pair<uint32, ObjectGuid>> DispelList; -class Spell +static const uint32 SPELL_INTERRUPT_NONPLAYER = 32747; + +class TC_GAME_API Spell { friend void Unit::SetCurrentCastSpell(Spell* pSpell); friend class SpellScript; @@ -694,21 +696,13 @@ class Spell ByteBuffer * m_effectExecuteData[MAX_SPELL_EFFECTS]; -#ifdef MAP_BASED_RAND_GEN - int32 irand(int32 min, int32 max) { return int32 (m_caster->GetMap()->mtRand.randInt(max - min)) + min; } - uint32 urand(uint32 min, uint32 max) { return m_caster->GetMap()->mtRand.randInt(max - min) + min; } - int32 rand32() { return m_caster->GetMap()->mtRand.randInt(); } - double rand_norm() { return m_caster->GetMap()->mtRand.randExc(); } - double rand_chance() { return m_caster->GetMap()->mtRand.randExc(100.0); } -#endif - Spell(Spell const& right) = delete; Spell& operator=(Spell const& right) = delete; }; namespace Trinity { - struct WorldObjectSpellTargetCheck + struct TC_GAME_API WorldObjectSpellTargetCheck { Unit* _caster; Unit* _referer; @@ -723,7 +717,7 @@ namespace Trinity bool operator()(WorldObject* target); }; - struct WorldObjectSpellNearbyTargetCheck : public WorldObjectSpellTargetCheck + struct TC_GAME_API WorldObjectSpellNearbyTargetCheck : public WorldObjectSpellTargetCheck { float _range; Position const* _position; @@ -732,7 +726,7 @@ namespace Trinity bool operator()(WorldObject* target); }; - struct WorldObjectSpellAreaTargetCheck : public WorldObjectSpellTargetCheck + struct TC_GAME_API WorldObjectSpellAreaTargetCheck : public WorldObjectSpellTargetCheck { float _range; Position const* _position; @@ -741,7 +735,7 @@ namespace Trinity bool operator()(WorldObject* target); }; - struct WorldObjectSpellConeTargetCheck : public WorldObjectSpellAreaTargetCheck + struct TC_GAME_API WorldObjectSpellConeTargetCheck : public WorldObjectSpellAreaTargetCheck { float _coneAngle; WorldObjectSpellConeTargetCheck(float coneAngle, float range, Unit* caster, @@ -749,7 +743,7 @@ namespace Trinity bool operator()(WorldObject* target); }; - struct WorldObjectSpellTrajTargetCheck : public WorldObjectSpellAreaTargetCheck + struct TC_GAME_API WorldObjectSpellTrajTargetCheck : public WorldObjectSpellAreaTargetCheck { WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo); bool operator()(WorldObject* target); @@ -758,7 +752,7 @@ namespace Trinity typedef void(Spell::*pEffect)(SpellEffIndex effIndex); -class SpellEvent : public BasicEvent +class TC_GAME_API SpellEvent : public BasicEvent { public: SpellEvent(Spell* spell); diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index 9535ca291eb..b0e3b6deeee 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -217,7 +217,7 @@ pEffect SpellEffects[TOTAL_SPELL_EFFECTS]= &Spell::EffectCreateItem2, //157 SPELL_EFFECT_CREATE_ITEM_2 create item or create item template and replace by some randon spell loot item &Spell::EffectMilling, //158 SPELL_EFFECT_MILLING milling &Spell::EffectRenamePet, //159 SPELL_EFFECT_ALLOW_RENAME_PET allow rename pet once again - &Spell::EffectNULL, //160 SPELL_EFFECT_160 1 spell - 45534 + &Spell::EffectForceCast, //160 SPELL_EFFECT_FORCE_CAST_2 &Spell::EffectSpecCount, //161 SPELL_EFFECT_TALENT_SPEC_COUNT second talent spec (learn/revert) &Spell::EffectActivateSpec, //162 SPELL_EFFECT_TALENT_SPEC_SELECT activate primary/secondary spec &Spell::EffectNULL, //163 unused @@ -250,13 +250,13 @@ void Spell::EffectResurrectNew(SpellEffIndex effIndex) Player* target = unitTarget->ToPlayer(); - if (target->isResurrectRequested()) // already have one active request + if (target->IsResurrectRequested()) // already have one active request return; uint32 health = damage; uint32 mana = m_spellInfo->Effects[effIndex].MiscValue; ExecuteLogEffectResurrect(effIndex, target); - target->setResurrectRequestData(m_caster->GetGUID(), m_caster->GetMapId(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), health, mana); + target->SetResurrectRequestData(m_caster, health, mana, 0); SendResurrectRequest(target); } @@ -556,7 +556,7 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) if (uint32 combo = player->GetComboPoints()) { float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); - damage += irand(int32(ap * combo * 0.03f), int32(ap * combo * 0.07f)); + damage += std::lroundf(ap * combo * 0.07f); // Eviscerate and Envenom Bonus Damage (item set effect) if (m_caster->HasAura(37169)) @@ -596,17 +596,13 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) if (Player* caster = m_caster->ToPlayer()) { // Add Ammo and Weapon damage plus RAP * 0.1 - if (Item* item = caster->GetWeaponForAttack(RANGED_ATTACK)) - { - ItemTemplate const* weaponTemplate = item->GetTemplate(); - float dmg_min = weaponTemplate->Damage[0].DamageMin; - float dmg_max = weaponTemplate->Damage[0].DamageMax; - if (dmg_max == 0.0f && dmg_min > dmg_max) - damage += int32(dmg_min); - else - damage += irand(int32(dmg_min), int32(dmg_max)); - damage += int32(caster->GetAmmoDPS() * weaponTemplate->Delay * 0.001f); - } + float dmg_min = caster->GetWeaponDamageRange(RANGED_ATTACK, MINDAMAGE); + float dmg_max = caster->GetWeaponDamageRange(RANGED_ATTACK, MAXDAMAGE); + if (dmg_max == 0.0f && dmg_min > dmg_max) + damage += int32(dmg_min); + else + damage += irand(int32(dmg_min), int32(dmg_max)); + damage += int32(caster->GetAmmoDPS() * caster->GetAttackTime(RANGED_ATTACK) * 0.001f); } } break; @@ -893,7 +889,7 @@ void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id); if (!spellInfo) { - TC_LOG_ERROR("spells", "Spell::EffectTriggerMissileSpell spell %u tried to trigger unknown spell %u", m_spellInfo->Id, triggered_spell_id); + TC_LOG_ERROR("spells", "Spell::EffectTriggerMissileSpell spell %u tried to trigger unknown spell %u.", m_spellInfo->Id, triggered_spell_id); return; } @@ -944,7 +940,7 @@ void Spell::EffectForceCast(SpellEffIndex effIndex) if (!spellInfo) { - TC_LOG_ERROR("spells", "Spell::EffectForceCast of spell %u: triggering unknown spell id %i", m_spellInfo->Id, triggered_spell_id); + TC_LOG_ERROR("spells", "Spell::EffectForceCast of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id); return; } @@ -996,7 +992,7 @@ void Spell::EffectTriggerRitualOfSummoning(SpellEffIndex effIndex) if (!spellInfo) { - TC_LOG_ERROR("spells", "EffectTriggerRitualOfSummoning of spell %u: triggering unknown spell id %i", m_spellInfo->Id, triggered_spell_id); + TC_LOG_ERROR("spells", "EffectTriggerRitualOfSummoning of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id); return; } @@ -1062,7 +1058,7 @@ void Spell::EffectTeleportUnits(SpellEffIndex /*effIndex*/) // If not exist data for dest location - return if (!m_targets.HasDst()) { - TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - does not have destination for spellId %u.", m_spellInfo->Id); + TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - does not have a destination for spellId %u.", m_spellInfo->Id); return; } @@ -1393,7 +1389,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) if (!targetAura) { - TC_LOG_ERROR("spells", "Target (%s) has aurastate AURA_STATE_SWIFTMEND but no matching aura.", unitTarget->GetGUID().ToString().c_str()); + TC_LOG_ERROR("spells", "Target (%s) has the aurastate AURA_STATE_SWIFTMEND, but no matching aura.", unitTarget->GetGUID().ToString().c_str()); return; } @@ -1683,6 +1679,8 @@ void Spell::EffectCreateItem2(SpellEffIndex effIndex) } else player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell); // create some random items + + player->UpdateCraftSkill(m_spellInfo->Id); } /// @todo ExecuteLogEffectCreateItem(i, m_spellInfo->Effects[i].ItemType); } @@ -1830,7 +1828,7 @@ void Spell::EffectEnergize(SpellEffIndex effIndex) sSpellMgr->GetSetOfSpellsInSpellGroup(SPELL_GROUP_ELIXIR_BATTLE, avalibleElixirs); for (std::set<uint32>::iterator itr = avalibleElixirs.begin(); itr != avalibleElixirs.end();) { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(*itr); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(*itr); if (spellInfo->SpellLevel < m_spellInfo->SpellLevel || spellInfo->SpellLevel > unitTarget->getLevel()) avalibleElixirs.erase(itr++); else if (sSpellMgr->IsSpellMemberOfSpellGroup(*itr, SPELL_GROUP_ELIXIR_SHATTRATH)) @@ -1886,7 +1884,7 @@ void Spell::SendLoot(ObjectGuid guid, LootType loottype) // Players shouldn't be able to loot gameobjects that are currently despawned if (!gameObjTarget->isSpawned() && !player->IsGameMaster()) { - TC_LOG_ERROR("spells", "Possible hacking attempt: Player %s [guid: %u] tried to loot a gameobject [entry: %u id: %u] which is on respawn time without being in GM mode!", + TC_LOG_ERROR("spells", "Possible hacking attempt: Player %s [guid: %u] tried to loot a gameobject [entry: %u id: %u] which is on respawn timer without being in GM mode!", player->GetName().c_str(), player->GetGUID().GetCounter(), gameObjTarget->GetEntry(), gameObjTarget->GetGUID().GetCounter()); return; } @@ -2110,8 +2108,7 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) else if (player->IsBankPos(pos)) { ItemPosCountVec dest; - uint8 msg = player->CanBankItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true); - if (msg == EQUIP_ERR_OK) + if (player->CanBankItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true) == EQUIP_ERR_OK) { player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); @@ -2133,7 +2130,7 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); - uint8 msg = player->CanEquipItem(m_CastItem->GetSlot(), dest, pNewItem, true); + InventoryResult msg = player->CanEquipItem(m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK || msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) { @@ -2191,7 +2188,7 @@ void Spell::EffectSummonType(SpellEffIndex effIndex) SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(m_spellInfo->Effects[effIndex].MiscValueB); if (!properties) { - TC_LOG_ERROR("spells", "EffectSummonType: Unhandled summon type %u", m_spellInfo->Effects[effIndex].MiscValueB); + TC_LOG_ERROR("spells", "EffectSummonType: Unhandled summon type %u.", m_spellInfo->Effects[effIndex].MiscValueB); return; } @@ -2379,7 +2376,7 @@ void Spell::EffectLearnSpell(SpellEffIndex effIndex) uint32 spellToLearn = (m_spellInfo->Id == 483 || m_spellInfo->Id == 55884) ? damage : m_spellInfo->Effects[effIndex].TriggerSpell; player->LearnSpell(spellToLearn, false); - TC_LOG_DEBUG("spells", "Spell: Player %u has learned spell %u from NpcGUID=%u", player->GetGUID().GetCounter(), spellToLearn, m_caster->GetGUID().GetCounter()); + TC_LOG_DEBUG("spells", "Spell: Player %u has learned spell %u from NpcGUID: %u", player->GetGUID().GetCounter(), spellToLearn, m_caster->GetGUID().GetCounter()); } void Spell::EffectDispel(SpellEffIndex effIndex) @@ -2758,7 +2755,7 @@ void Spell::EffectEnchantItemPrismatic(SpellEffIndex effIndex) } if (!add_socket) { - TC_LOG_ERROR("spells", "Spell::EffectEnchantItemPrismatic: attempt apply enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u) but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not suppoted yet.", + TC_LOG_ERROR("spells", "Spell::EffectEnchantItemPrismatic: attempt to apply the enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u), but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not supported yet.", m_spellInfo->Id, SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC, ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET); return; } @@ -2823,7 +2820,7 @@ void Spell::EffectEnchantItemTmp(SpellEffIndex effIndex) case 10: spell_id = 36758; break; // 14% case 11: spell_id = 36760; break; // 20% default: - TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW", damage); + TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW.", damage); return; } @@ -2857,14 +2854,14 @@ void Spell::EffectEnchantItemTmp(SpellEffIndex effIndex) if (!enchant_id) { - TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) have 0 as enchanting id", m_spellInfo->Id, effIndex); + TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has enchanting id 0.", m_spellInfo->Id, effIndex); return; } SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) { - TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) have not existed enchanting id %u ", m_spellInfo->Id, effIndex, enchant_id); + TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has a non-existing enchanting id %u ", m_spellInfo->Id, effIndex, enchant_id); return; } @@ -3020,6 +3017,12 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) //OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation()); //OldSummon->SetMap(owner->GetMap()); //owner->GetMap()->Add(OldSummon->ToCreature()); + if (OldSummon->getPetType() == SUMMON_PET) + { + OldSummon->SetHealth(OldSummon->GetMaxHealth()); + OldSummon->SetPower(OldSummon->getPowerType(), + OldSummon->GetMaxPower(OldSummon->getPowerType())); + } if (owner->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled()) owner->ToPlayer()->PetSpellInitialize(); @@ -3506,7 +3509,7 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) Map* map = target->GetMap(); if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, - m_caster->GetPhaseMask(), x, y, z, target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) { delete pGameObj; return; @@ -3531,7 +3534,7 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) { GameObject* linkedGO = new GameObject; if (linkedGO->Create(map->GenerateLowGuid<HighGuid::GameObject>(), linkedEntry, map, - m_caster->GetPhaseMask(), x, y, z, target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) { linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); linkedGO->SetSpellId(m_spellInfo->Id); @@ -3662,16 +3665,6 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) m_caster->CastSpell(unitTarget, 22682, true); return; } - // Decimate - case 28374: - case 54426: - if (unitTarget) - { - int32 decimateDamage = int32(unitTarget->GetHealth()) - int32(unitTarget->CountPctFromMaxHealth(5)); - if (decimateDamage > 0) - m_caster->CastCustomSpell(28375, SPELLVALUE_BASE_POINT0, decimateDamage, unitTarget); - } - return; // Mirren's Drinking Hat case 29830: { @@ -3782,28 +3775,6 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) break; } - // Roll Dice - Decahedral Dwarven Dice - case 47770: - { - char buf[128]; - const char *gender = "his"; - if (m_caster->getGender() > 0) - gender = "her"; - sprintf(buf, "%s rubs %s [Decahedral Dwarven Dice] between %s hands and rolls. One %u and one %u.", m_caster->GetName().c_str(), gender, gender, urand(1, 10), urand(1, 10)); - m_caster->TextEmote(buf); - break; - } - // Roll 'dem Bones - Worn Troll Dice - case 47776: - { - char buf[128]; - const char *gender = "his"; - if (m_caster->getGender() > 0) - gender = "her"; - sprintf(buf, "%s causually tosses %s [Worn Troll Dice]. One %u and one %u.", m_caster->GetName().c_str(), gender, urand(1, 6), urand(1, 6)); - m_caster->TextEmote(buf); - break; - } // Death Knight Initiate Visual case 51519: { @@ -3980,7 +3951,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) case 31893: spell_heal = 48084; break; case 31883: spell_heal = 48085; break; default: - TC_LOG_ERROR("spells", "Unknown Lightwell spell caster %u", m_caster->GetEntry()); + TC_LOG_ERROR("spells", "Unknown Lightwell spell caster %u.", m_caster->GetEntry()); return; } @@ -4152,13 +4123,16 @@ void Spell::EffectDuel(SpellEffIndex effIndex) uint32 gameobject_id = m_spellInfo->Effects[effIndex].MiscValue; - Map* map = m_caster->GetMap(); - if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, - map, m_caster->GetPhaseMask(), - m_caster->GetPositionX()+(unitTarget->GetPositionX()-m_caster->GetPositionX())/2, - m_caster->GetPositionY()+(unitTarget->GetPositionY()-m_caster->GetPositionY())/2, + Position const pos = + { + m_caster->GetPositionX() + (unitTarget->GetPositionX() - m_caster->GetPositionX()) / 2, + m_caster->GetPositionY() + (unitTarget->GetPositionY() - m_caster->GetPositionY()) / 2, m_caster->GetPositionZ(), - m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY)) + m_caster->GetOrientation() + }; + + Map* map = m_caster->GetMap(); + if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, m_caster->GetPhaseMask(), pos, G3D::Quat(), 0, GO_STATE_READY)) { delete pGameObj; return; @@ -4219,7 +4193,7 @@ void Spell::EffectStuck(SpellEffIndex /*effIndex*/) return; TC_LOG_DEBUG("spells", "Spell Effect: Stuck"); - TC_LOG_DEBUG("spells", "Player %s (guid %u) used auto-unstuck future at map %u (%f, %f, %f)", player->GetName().c_str(), player->GetGUID().GetCounter(), player->GetMapId(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); + TC_LOG_DEBUG("spells", "Player %s (guid %u) used the auto-unstuck feature at map %u (%f, %f, %f).", player->GetName().c_str(), player->GetGUID().GetCounter(), player->GetMapId(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); if (player->IsInFlight()) return; @@ -4245,20 +4219,7 @@ void Spell::EffectSummonPlayer(SpellEffIndex /*effIndex*/) if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; - // Evil Twin (ignore player summon, but hide this for summoner) - if (unitTarget->HasAura(23445)) - return; - - float x, y, z; - m_caster->GetPosition(x, y, z); - - unitTarget->ToPlayer()->SetSummonPoint(m_caster->GetMapId(), x, y, z); - - WorldPacket data(SMSG_SUMMON_REQUEST, 8+4+4); - data << uint64(m_caster->GetGUID()); // summoner guid - data << uint32(m_caster->GetZoneId()); // summoner zone - data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs - unitTarget->ToPlayer()->GetSession()->SendPacket(&data); + unitTarget->ToPlayer()->SendSummonRequestFrom(m_caster); } void Spell::EffectActivateObject(SpellEffIndex /*effIndex*/) @@ -4504,7 +4465,7 @@ void Spell::EffectSummonObject(SpellEffIndex effIndex) Map* map = m_caster->GetMap(); if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), go_id, map, - m_caster->GetPhaseMask(), x, y, z, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(x, y, z, m_caster->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) { delete go; return; @@ -4536,7 +4497,7 @@ void Spell::EffectResurrect(SpellEffIndex effIndex) Player* target = unitTarget->ToPlayer(); - if (target->isResurrectRequested()) // already have one active request + if (target->IsResurrectRequested()) // already have one active request return; uint32 health = target->CountPctFromMaxHealth(damage); @@ -4544,7 +4505,7 @@ void Spell::EffectResurrect(SpellEffIndex effIndex) ExecuteLogEffectResurrect(effIndex, target); - target->setResurrectRequestData(m_caster->GetGUID(), m_caster->GetMapId(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), health, mana); + target->SetResurrectRequestData(m_caster, health, mana, 0); SendResurrectRequest(target); } @@ -5101,7 +5062,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) if (!goinfo) { - TC_LOG_ERROR("sql.sql", "Gameobject (Entry: %u) not exist and not created at spell (ID: %u) cast", name_id, m_spellInfo->Id); + TC_LOG_ERROR("sql.sql", "Gameobject (Entry: %u) does not exist and is not created by spell (ID: %u) cast.", name_id, m_spellInfo->Id); return; } @@ -5133,7 +5094,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) GameObject* pGameObj = new GameObject; if (!pGameObj->Create(cMap->GenerateLowGuid<HighGuid::GameObject>(), name_id, cMap, - m_caster->GetPhaseMask(), fx, fy, fz, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(fx, fy, fz, m_caster->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) { delete pGameObj; return; @@ -5199,7 +5160,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) { GameObject* linkedGO = new GameObject; if (linkedGO->Create(cMap->GenerateLowGuid<HighGuid::GameObject>(), linkedEntry, cMap, - m_caster->GetPhaseMask(), fx, fy, fz, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(fx, fy, fz, m_caster->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) { linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); //linkedGO->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()); @@ -5521,7 +5482,7 @@ void Spell::EffectActivateRune(SpellEffIndex effIndex) for (uint32 l = 0; l + 1 < MAX_RUNES && count > 0; ++l) { // Check if both runes are on cd as that is the only time when this needs to come into effect - if ((player->GetRuneCooldown(l) && player->GetCurrentRune(l) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB)) && (player->GetRuneCooldown(l+1) && player->GetCurrentRune(l+1) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB))) + if ((player->GetRuneCooldown(l) && player->GetBaseRune(l) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB)) && (player->GetRuneCooldown(l+1) && player->GetBaseRune(l+1) == RuneType(m_spellInfo->Effects[effIndex].MiscValueB))) { // Should always update the rune with the lowest cd if (l + 1 < MAX_RUNES && player->GetRuneCooldown(l) >= player->GetRuneCooldown(l+1)) @@ -5742,7 +5703,7 @@ void Spell::EffectPlayMusic(SpellEffIndex effIndex) if (!sSoundEntriesStore.LookupEntry(soundid)) { - TC_LOG_ERROR("spells", "EffectPlayMusic: Sound (Id: %u) not exist in spell %u.", soundid, m_spellInfo->Id); + TC_LOG_ERROR("spells", "EffectPlayMusic: Sound (Id: %u) does not exist in spell %u.", soundid, m_spellInfo->Id); return; } @@ -5799,7 +5760,7 @@ void Spell::EffectPlaySound(SpellEffIndex effIndex) if (!sSoundEntriesStore.LookupEntry(soundId)) { - TC_LOG_ERROR("spells", "EffectPlaySound: Sound (Id: %u) not exist in spell %u.", soundId, m_spellInfo->Id); + TC_LOG_ERROR("spells", "EffectPlaySound: Sound (Id: %u) does not exist in spell %u.", soundId, m_spellInfo->Id); return; } diff --git a/src/server/game/Spells/SpellHistory.cpp b/src/server/game/Spells/SpellHistory.cpp index adf5fc47c77..31490bea29b 100644 --- a/src/server/game/Spells/SpellHistory.cpp +++ b/src/server/game/Spells/SpellHistory.cpp @@ -373,7 +373,7 @@ void SpellHistory::SendCooldownEvent(SpellInfo const* spellInfo, uint32 itemId / player->SendDirectMessage(&data); if (startCooldown) - StartCooldown(sSpellMgr->EnsureSpellInfo(categoryItr->second->SpellId), itemId, spell); + StartCooldown(sSpellMgr->AssertSpellInfo(categoryItr->second->SpellId), itemId, spell); } WorldPacket data(SMSG_COOLDOWN_EVENT, 4 + 8); @@ -483,7 +483,7 @@ bool SpellHistory::HasCooldown(SpellInfo const* spellInfo, uint32 itemId /*= 0*/ bool SpellHistory::HasCooldown(uint32 spellId, uint32 itemId /*= 0*/, bool ignoreCategoryCooldown /*= false*/) const { - return HasCooldown(sSpellMgr->EnsureSpellInfo(spellId), itemId, ignoreCategoryCooldown); + return HasCooldown(sSpellMgr->AssertSpellInfo(spellId), itemId, ignoreCategoryCooldown); } uint32 SpellHistory::GetRemainingCooldown(SpellInfo const* spellInfo) const @@ -533,7 +533,7 @@ void SpellHistory::LockSpellSchool(SpellSchoolMask schoolMask, uint32 lockoutTim else { Creature* creatureOwner = _owner->ToCreature(); - for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) + for (uint8 i = 0; i < MAX_CREATURE_SPELLS; ++i) if (creatureOwner->m_spells[i]) knownSpells.insert(creatureOwner->m_spells[i]); } @@ -542,7 +542,7 @@ void SpellHistory::LockSpellSchool(SpellSchoolMask schoolMask, uint32 lockoutTim WorldPacket spellCooldowns; for (uint32 spellId : knownSpells) { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(spellId); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(spellId); if (spellInfo->IsCooldownStartedOnEvent()) continue; @@ -688,7 +688,7 @@ void SpellHistory::RestoreCooldownStateAfterDuel() // add all profession CDs created while in duel (if any) for (auto itr = _spellCooldowns.begin(); itr != _spellCooldowns.end(); ++itr) { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); if (spellInfo->RecoveryTime > 10 * MINUTE * IN_MILLISECONDS || spellInfo->CategoryRecoveryTime > 10 * MINUTE * IN_MILLISECONDS) diff --git a/src/server/game/Spells/SpellHistory.h b/src/server/game/Spells/SpellHistory.h index f0a53fe130d..ccc8a7daa96 100644 --- a/src/server/game/Spells/SpellHistory.h +++ b/src/server/game/Spells/SpellHistory.h @@ -31,7 +31,7 @@ class SpellInfo; class Unit; struct SpellCategoryEntry; -class SpellHistory +class TC_GAME_API SpellHistory { public: typedef std::chrono::system_clock Clock; diff --git a/src/server/game/Spells/SpellInfo.cpp b/src/server/game/Spells/SpellInfo.cpp index 736bbfb7fa9..ac157b48783 100644 --- a/src/server/game/Spells/SpellInfo.cpp +++ b/src/server/game/Spells/SpellInfo.cpp @@ -418,7 +418,8 @@ int32 SpellEffectInfo::CalcValue(Unit const* caster, int32 const* bp, Unit const level = int32(_spellInfo->MaxLevel); else if (level < int32(_spellInfo->BaseLevel)) level = int32(_spellInfo->BaseLevel); - level -= int32(_spellInfo->SpellLevel); + if (!_spellInfo->IsPassive()) + level -= int32(_spellInfo->SpellLevel); basePoints += int32(level * basePointsPerLevel); } @@ -524,10 +525,10 @@ float SpellEffectInfo::CalcValueMultiplier(Unit* caster, Spell* spell) const float SpellEffectInfo::CalcDamageMultiplier(Unit* caster, Spell* spell) const { - float multiplier = DamageMultiplier; + float multiplierPercent = DamageMultiplier * 100.0f; if (Player* modOwner = (caster ? caster->GetSpellModOwner() : NULL)) - modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_DAMAGE_MULTIPLIER, multiplier, spell); - return multiplier; + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_DAMAGE_MULTIPLIER, multiplierPercent, spell); + return multiplierPercent / 100.0f; } bool SpellEffectInfo::HasRadius() const @@ -754,7 +755,7 @@ SpellEffectInfo::StaticData SpellEffectInfo::_data[TOTAL_SPELL_EFFECTS] = {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 157 SPELL_EFFECT_CREATE_ITEM_2 {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_ITEM}, // 158 SPELL_EFFECT_MILLING {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 159 SPELL_EFFECT_ALLOW_RENAME_PET - {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 160 SPELL_EFFECT_160 + {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 160 SPELL_EFFECT_FORCE_CAST_2 {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 161 SPELL_EFFECT_TALENT_SPEC_COUNT {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 162 SPELL_EFFECT_TALENT_SPEC_SELECT {EFFECT_IMPLICIT_TARGET_EXPLICIT, TARGET_OBJECT_TYPE_UNIT}, // 163 SPELL_EFFECT_163 @@ -1226,18 +1227,14 @@ bool SpellInfo::CanDispelAura(SpellInfo const* aura) const if (HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) && !aura->IsDeathPersistent()) return true; - // These auras (Cyclone for example) are not dispelable - if (aura->HasAttribute(SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE)) - return false; - - // Divine Shield etc can dispel auras if they don't ignore school immunity - if (HasAttribute(SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) && !aura->IsDeathPersistent()) - return true; - // These auras (like Divine Shield) can't be dispelled if (aura->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY)) return false; + // These auras (Cyclone for example) are not dispelable + if (aura->HasAttribute(SPELL_ATTR1_UNAFFECTED_BY_SCHOOL_IMMUNE)) + return false; + return true; } diff --git a/src/server/game/Spells/SpellInfo.h b/src/server/game/Spells/SpellInfo.h index ba658c885fa..1530235174a 100644 --- a/src/server/game/Spells/SpellInfo.h +++ b/src/server/game/Spells/SpellInfo.h @@ -187,13 +187,14 @@ enum SpellCustomAttributes SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER = 0x00010000, SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET = 0x00020000, SPELL_ATTR0_CU_ALLOW_INFLIGHT_TARGET = 0x00040000, + SPELL_ATTR0_CU_NEEDS_AMMO_DATA = 0x00080000, SPELL_ATTR0_CU_NEGATIVE = SPELL_ATTR0_CU_NEGATIVE_EFF0 | SPELL_ATTR0_CU_NEGATIVE_EFF1 | SPELL_ATTR0_CU_NEGATIVE_EFF2 }; uint32 GetTargetFlagMask(SpellTargetObjectTypes objType); -class SpellImplicitTargetInfo +class TC_GAME_API SpellImplicitTargetInfo { private: Targets _target; @@ -224,7 +225,7 @@ private: static StaticData _data[TOTAL_SPELL_TARGETS]; }; -class SpellEffectInfo +class TC_GAME_API SpellEffectInfo { SpellInfo const* _spellInfo; uint8 _effIndex; @@ -290,7 +291,7 @@ private: static StaticData _data[TOTAL_SPELL_EFFECTS]; }; -class SpellInfo +class TC_GAME_API SpellInfo { public: uint32 Id; diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index f5bb1c920fe..ed0d95f0a58 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -353,6 +353,12 @@ SpellMgr::~SpellMgr() UnloadSpellInfoStore(); } +SpellMgr* SpellMgr::instance() +{ + static SpellMgr instance; + return &instance; +} + /// Some checks for spells, to prevent adding deprecated/broken spells for trainers, spell book, etc bool SpellMgr::IsSpellValid(SpellInfo const* spellInfo, Player* player, bool msg) { @@ -376,29 +382,29 @@ bool SpellMgr::IsSpellValid(SpellInfo const* spellInfo, Player* player, bool msg { if (spellInfo->Effects[i].ItemType == 0) { - // skip auto-loot crafting spells, its not need explicit item info (but have special fake items sometime) + // skip auto-loot crafting spells, it does not need explicit item info (but has special fake items sometimes). if (!spellInfo->IsLootCrafting()) { if (msg) { if (player) - ChatHandler(player->GetSession()).PSendSysMessage("Craft spell %u not have create item entry.", spellInfo->Id); + ChatHandler(player->GetSession()).PSendSysMessage("The craft spell %u does not have a create item entry.", spellInfo->Id); else - TC_LOG_ERROR("sql.sql", "Craft spell %u not have create item entry.", spellInfo->Id); + TC_LOG_ERROR("sql.sql", "The craft spell %u does not have a create item entry.", spellInfo->Id); } return false; } } - // also possible IsLootCrafting case but fake item must exist anyway + // also possible IsLootCrafting case but fake items must exist anyway else if (!sObjectMgr->GetItemTemplate(spellInfo->Effects[i].ItemType)) { if (msg) { if (player) - ChatHandler(player->GetSession()).PSendSysMessage("Craft spell %u create not-exist in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); + ChatHandler(player->GetSession()).PSendSysMessage("Craft spell %u has created a non-existing item in DB (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); else - TC_LOG_ERROR("sql.sql", "Craft spell %u create not-exist in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); + TC_LOG_ERROR("sql.sql", "Craft spell %u has created a non-existing item in DB (Entry: %u) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); } return false; } @@ -434,9 +440,9 @@ bool SpellMgr::IsSpellValid(SpellInfo const* spellInfo, Player* player, bool msg if (msg) { if (player) - ChatHandler(player->GetSession()).PSendSysMessage("Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Reagent[j]); + ChatHandler(player->GetSession()).PSendSysMessage("Craft spell %u refers a non-existing reagent in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Reagent[j]); else - TC_LOG_ERROR("sql.sql", "Craft spell %u have not-exist reagent in DB item (Entry: %u) and then...", spellInfo->Id, spellInfo->Reagent[j]); + TC_LOG_ERROR("sql.sql", "Craft spell %u refers to a non-existing reagent in DB, item (Entry: %u) and then...", spellInfo->Id, spellInfo->Reagent[j]); } return false; } @@ -455,7 +461,7 @@ uint32 SpellMgr::GetSpellDifficultyId(uint32 spellId) const void SpellMgr::SetSpellDifficultyId(uint32 spellId, uint32 id) { if (uint32 i = GetSpellDifficultyId(spellId)) - TC_LOG_ERROR("spells", "SpellMgr::SetSpellDifficultyId: Spell %u has already spellDifficultyId %u. Will override with spellDifficultyId %u.", spellId, i, id); + TC_LOG_ERROR("spells", "SpellMgr::SetSpellDifficultyId: The spell %u already has spellDifficultyId %u. Will override with spellDifficultyId %u.", spellId, i, id); mSpellDifficultySearcherMap[spellId] = id; } @@ -470,7 +476,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con uint32 mode = uint32(caster->GetMap()->GetSpawnMode()); if (mode >= MAX_DIFFICULTY) { - TC_LOG_ERROR("spells", "SpellMgr::GetSpellIdForDifficulty: Incorrect Difficulty for spell %u.", spellId); + TC_LOG_ERROR("spells", "SpellMgr::GetSpellIdForDifficulty: Incorrect difficulty for spell %u.", spellId); return spellId; //return source spell } @@ -481,7 +487,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con SpellDifficultyEntry const* difficultyEntry = sSpellDifficultyStore.LookupEntry(difficultyId); if (!difficultyEntry) { - TC_LOG_ERROR("spells", "SpellMgr::GetSpellIdForDifficulty: SpellDifficultyEntry not found for spell %u. This should never happen.", spellId); + TC_LOG_ERROR("spells", "SpellMgr::GetSpellIdForDifficulty: SpellDifficultyEntry was not found for spell %u. This should never happen.", spellId); return spellId; //return source spell } @@ -874,7 +880,7 @@ bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, Spell // For melee triggers if (procSpell == NULL) { - // Check (if set) for school (melee attack have Normal school) + // Check (if set) for school (melee attack has Normal school) if (spellProcEvent->schoolMask && (spellProcEvent->schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) return false; } @@ -894,7 +900,7 @@ bool SpellMgr::IsSpellProcEventCanTriggeredBy(SpellInfo const* spellProto, Spell if (!(spellProcEvent->spellFamilyMask & procSpell->SpellFamilyFlags)) return false; hasFamilyMask = true; - // Some spells are not considered as active even with have spellfamilyflags + // Some spells are not considered as active even with spellfamilyflags set if (!(procEvent_procEx & PROC_EX_ONLY_ACTIVE_SPELL)) active = true; } @@ -949,11 +955,11 @@ SpellProcEntry const* SpellMgr::GetSpellProcEntry(uint32 spellId) const bool SpellMgr::CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) const { // proc type doesn't match - if (!(eventInfo.GetTypeMask() & procEntry.typeMask)) + if (!(eventInfo.GetTypeMask() & procEntry.ProcFlags)) return false; // check XP or honor target requirement - if (procEntry.attributesMask & PROC_ATTR_REQ_EXP_OR_HONOR) + if (procEntry.AttributesMask & PROC_ATTR_REQ_EXP_OR_HONOR) if (Player* actor = eventInfo.GetActor()->ToPlayer()) if (eventInfo.GetActionTarget() && !actor->isHonorOrXPTarget(eventInfo.GetActionTarget())) return false; @@ -963,7 +969,7 @@ bool SpellMgr::CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcE return true; // check school mask (if set) for other trigger types - if (procEntry.schoolMask && !(eventInfo.GetSchoolMask() & procEntry.schoolMask)) + if (procEntry.SchoolMask && !(eventInfo.GetSchoolMask() & procEntry.SchoolMask)) return false; // check spell family name/flags (if set) for spells @@ -971,31 +977,31 @@ bool SpellMgr::CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcE { SpellInfo const* eventSpellInfo = eventInfo.GetSpellInfo(); - if (procEntry.spellFamilyName && eventSpellInfo && (procEntry.spellFamilyName != eventSpellInfo->SpellFamilyName)) + if (procEntry.SpellFamilyName && eventSpellInfo && (procEntry.SpellFamilyName != eventSpellInfo->SpellFamilyName)) return false; - if (procEntry.spellFamilyMask && eventSpellInfo && !(procEntry.spellFamilyMask & eventSpellInfo->SpellFamilyFlags)) + if (procEntry.SpellFamilyMask && eventSpellInfo && !(procEntry.SpellFamilyMask & eventSpellInfo->SpellFamilyFlags)) return false; } // check spell type mask (if set) if (eventInfo.GetTypeMask() & (SPELL_PROC_FLAG_MASK | PERIODIC_PROC_FLAG_MASK)) { - if (procEntry.spellTypeMask && !(eventInfo.GetSpellTypeMask() & procEntry.spellTypeMask)) + if (procEntry.SpellTypeMask && !(eventInfo.GetSpellTypeMask() & procEntry.SpellTypeMask)) return false; } // check spell phase mask if (eventInfo.GetTypeMask() & REQ_SPELL_PHASE_PROC_FLAG_MASK) { - if (!(eventInfo.GetSpellPhaseMask() & procEntry.spellPhaseMask)) + if (!(eventInfo.GetSpellPhaseMask() & procEntry.SpellPhaseMask)) return false; } // check hit mask (on taken hit or on done hit, but not on spell cast phase) if ((eventInfo.GetTypeMask() & TAKEN_HIT_PROC_FLAG_MASK) || ((eventInfo.GetTypeMask() & DONE_HIT_PROC_FLAG_MASK) && !(eventInfo.GetSpellPhaseMask() & PROC_SPELL_PHASE_CAST))) { - uint32 hitMask = procEntry.hitMask; + uint32 hitMask = procEntry.HitMask; // get default values if hit mask not set if (!hitMask) { @@ -1121,27 +1127,27 @@ SpellAreaForAreaMapBounds SpellMgr::GetSpellAreaForAreaMapBounds(uint32 area_id) bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 newArea) const { - if (gender != GENDER_NONE) // not in expected gender + if (gender != GENDER_NONE) // is not expected gender if (!player || gender != player->getGender()) return false; - if (raceMask) // not in expected race + if (raceMask) // is not expected race if (!player || !(raceMask & player->getRaceMask())) return false; - if (areaId) // not in expected zone + if (areaId) // is not in expected zone if (newZone != areaId && newArea != areaId) return false; - if (questStart) // not in expected required quest state + if (questStart) // is not in expected required quest state if (!player || (((1 << player->GetQuestStatus(questStart)) & questStartStatus) == 0)) return false; - if (questEnd) // not in expected forbidden quest state + if (questEnd) // is not in expected forbidden quest state if (!player || (((1 << player->GetQuestStatus(questEnd)) & questEndStatus) == 0)) return false; - if (auraSpell) // not have expected aura + if (auraSpell) // does not have expected aura if (!player || (auraSpell > 0 && !player->HasAura(auraSpell)) || (auraSpell < 0 && player->HasAura(-auraSpell))) return false; @@ -1341,7 +1347,7 @@ void SpellMgr::LoadSpellRanks() SpellInfo const* first = GetSpellInfo(lastSpell); if (!first) { - TC_LOG_ERROR("sql.sql", "Spell rank identifier(first_spell_id) %u listed in `spell_ranks` does not exist!", lastSpell); + TC_LOG_ERROR("sql.sql", "The spell rank identifier(first_spell_id) %u listed in `spell_ranks` does not exist!", lastSpell); continue; } // check if chain is long enough @@ -1358,14 +1364,14 @@ void SpellMgr::LoadSpellRanks() SpellInfo const* spell = GetSpellInfo(itr->first); if (!spell) { - TC_LOG_ERROR("sql.sql", "Spell %u (rank %u) listed in `spell_ranks` for chain %u does not exist!", itr->first, itr->second, lastSpell); + TC_LOG_ERROR("sql.sql", "The spell %u (rank %u) listed in `spell_ranks` for chain %u does not exist!", itr->first, itr->second, lastSpell); valid = false; break; } ++curRank; if (itr->second != curRank) { - TC_LOG_ERROR("sql.sql", "Spell %u (rank %u) listed in `spell_ranks` for chain %u does not have proper rank value(should be %u)!", itr->first, itr->second, lastSpell, curRank); + TC_LOG_ERROR("sql.sql", "The spell %u (rank %u) listed in `spell_ranks` for chain %u does not have a proper rank value (should be %u)!", itr->first, itr->second, lastSpell, curRank); valid = false; break; } @@ -1381,7 +1387,7 @@ void SpellMgr::LoadSpellRanks() int32 addedSpell = itr->first; if (mSpellInfoMap[addedSpell]->ChainEntry) - TC_LOG_ERROR("sql.sql", "Spell %u (rank: %u, first: %u) listed in `spell_ranks` has already ChainEntry from dbc.", addedSpell, itr->second, lastSpell); + TC_LOG_ERROR("sql.sql", "The spell %u (rank: %u, first: %u) listed in `spell_ranks` already has ChainEntry from dbc.", addedSpell, itr->second, lastSpell); mSpellChains[addedSpell].first = GetSpellInfo(lastSpell); mSpellChains[addedSpell].last = GetSpellInfo(rankChain.back().first); @@ -1435,26 +1441,26 @@ void SpellMgr::LoadSpellRequired() SpellInfo const* spell = GetSpellInfo(spell_id); if (!spell) { - TC_LOG_ERROR("sql.sql", "spell_id %u in `spell_required` table is not found in dbcs, skipped", spell_id); + TC_LOG_ERROR("sql.sql", "spell_id %u in `spell_required` table could not be found in dbc, skipped.", spell_id); continue; } SpellInfo const* reqSpell = GetSpellInfo(spell_req); if (!reqSpell) { - TC_LOG_ERROR("sql.sql", "req_spell %u in `spell_required` table is not found in dbcs, skipped", spell_req); + TC_LOG_ERROR("sql.sql", "req_spell %u in `spell_required` table could not be found in dbc, skipped.", spell_req); continue; } if (spell->IsRankOf(reqSpell)) { - TC_LOG_ERROR("sql.sql", "req_spell %u and spell_id %u in `spell_required` table are ranks of the same spell, entry not needed, skipped", spell_req, spell_id); + TC_LOG_ERROR("sql.sql", "req_spell %u and spell_id %u in `spell_required` table are ranks of the same spell, entry not needed, skipped.", spell_req, spell_id); continue; } if (IsSpellRequiringSpell(spell_id, spell_req)) { - TC_LOG_ERROR("sql.sql", "duplicated entry of req_spell %u and spell_id %u in `spell_required`, skipped", spell_req, spell_id); + TC_LOG_ERROR("sql.sql", "Duplicate entry of req_spell %u and spell_id %u in `spell_required`, skipped.", spell_req, spell_id); continue; } @@ -1532,19 +1538,19 @@ void SpellMgr::LoadSpellLearnSpells() if (!GetSpellInfo(spell_id)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_learn_spell` does not exist", spell_id); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_learn_spell` does not exist.", spell_id); continue; } if (!GetSpellInfo(node.spell)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_learn_spell` learning not existed spell %u", spell_id, node.spell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_learn_spell` learning non-existing spell %u.", spell_id, node.spell); continue; } if (GetTalentSpellCost(node.spell)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_learn_spell` attempt learning talent spell %u, skipped", spell_id, node.spell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_learn_spell` attempts learning talent spell %u, skipped.", spell_id, node.spell); continue; } @@ -1586,7 +1592,7 @@ void SpellMgr::LoadSpellLearnSpells() { if (itr->second.spell == dbc_node.spell) { - TC_LOG_ERROR("sql.sql", "Spell %u auto-learn spell %u in spell.dbc then the record in `spell_learn_spell` is redundant, please fix DB.", + TC_LOG_ERROR("sql.sql", "The spell %u is an auto-learn spell %u in spell.dbc and the record in `spell_learn_spell` is redundant. Please update your DB.", spell, dbc_node.spell); found = true; break; @@ -1663,7 +1669,7 @@ void SpellMgr::LoadSpellTargetPositions() } else { - TC_LOG_ERROR("sql.sql", "Spell (Id: %u, effIndex: %u) listed in `spell_target_position` does not have target TARGET_DEST_DB (17).", Spell_ID, effIndex); + TC_LOG_ERROR("sql.sql", "Spell (Id: %u, effIndex: %u) listed in `spell_target_position` does not have a target TARGET_DEST_DB (17).", Spell_ID, effIndex); continue; } @@ -1700,7 +1706,7 @@ void SpellMgr::LoadSpellTargetPositions() if (found) { if (!sSpellMgr->GetSpellTargetPosition(i)) - TC_LOG_DEBUG("spells", "Spell (ID: %u) does not have record in `spell_target_position`", i); + TC_LOG_DEBUG("spells", "Spell (ID: %u) does not have a record in `spell_target_position`.", i); } }*/ @@ -1759,12 +1765,12 @@ void SpellMgr::LoadSpellGroups() if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_group` does not exist", itr->second); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_group` does not exist", itr->second); mSpellGroupSpell.erase(itr++); } else if (spellInfo->GetRank() > 1) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_group` is not first rank of spell", itr->second); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_group` is not the first rank of the spell.", itr->second); mSpellGroupSpell.erase(itr++); } else @@ -1810,7 +1816,7 @@ void SpellMgr::LoadSpellGroupStackRules() uint8 stack_rule = fields[1].GetInt8(); if (stack_rule >= SPELL_GROUP_STACK_RULE_MAX) { - TC_LOG_ERROR("sql.sql", "SpellGroupStackRule %u listed in `spell_group_stack_rules` does not exist", stack_rule); + TC_LOG_ERROR("sql.sql", "SpellGroupStackRule %u listed in `spell_group_stack_rules` does not exist.", stack_rule); continue; } @@ -1818,7 +1824,7 @@ void SpellMgr::LoadSpellGroupStackRules() if (spellGroup.first == spellGroup.second) { - TC_LOG_ERROR("sql.sql", "SpellGroup id %u listed in `spell_group_stack_rules` does not exist", group_id); + TC_LOG_ERROR("sql.sql", "SpellGroup id %u listed in `spell_group_stack_rules` does not exist.", group_id); continue; } @@ -1862,18 +1868,18 @@ void SpellMgr::LoadSpellProcEvents() SpellInfo const* spellInfo = GetSpellInfo(spellId); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc_event` does not exist", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc_event` does not exist.", spellId); continue; } if (allRanks) { if (!spellInfo->IsRanked()) - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc_event` with all ranks, but spell has no ranks.", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u is listed in `spell_proc_event` with all ranks, but spell has no ranks.", spellId); if (spellInfo->GetFirstRankSpell()->Id != uint32(spellId)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc_event` is not first rank of spell.", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc_event` is not first rank of spell.", spellId); continue; } } @@ -1895,12 +1901,12 @@ void SpellMgr::LoadSpellProcEvents() { if (mSpellProcEventMap.find(spellInfo->Id) != mSpellProcEventMap.end()) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc_event` already has its first rank in table.", spellInfo->Id); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc_event` already has its first rank in table.", spellInfo->Id); break; } if (!spellInfo->ProcFlags && !spellProcEvent.procFlags) - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc_event` probably not triggered spell", spellInfo->Id); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc_event` is probably not a triggered spell.", spellInfo->Id); mSpellProcEventMap[spellInfo->Id] = spellProcEvent; @@ -1923,8 +1929,11 @@ void SpellMgr::LoadSpellProcs() mSpellProcMap.clear(); // need for reload case - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 - QueryResult result = WorldDatabase.Query("SELECT spellId, schoolMask, spellFamilyName, spellFamilyMask0, spellFamilyMask1, spellFamilyMask2, typeMask, spellTypeMask, spellPhaseMask, hitMask, attributesMask, ratePerMinute, chance, cooldown, charges FROM spell_proc"); + // 0 1 2 3 4 5 + QueryResult result = WorldDatabase.Query("SELECT SpellId, SchoolMask, SpellFamilyName, SpellFamilyMask0, SpellFamilyMask1, SpellFamilyMask2, " + // 6 7 8 9 10 11 12 13 14 + "ProcFlags, SpellTypeMask, SpellPhaseMask, HitMask, AttributesMask, ProcsPerMinute, Chance, Cooldown, Charges FROM spell_proc"); + if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 spell proc conditions and data. DB table `spell_proc` is empty."); @@ -1948,101 +1957,90 @@ void SpellMgr::LoadSpellProcs() SpellInfo const* spellInfo = GetSpellInfo(spellId); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc` does not exist", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc` does not exist", spellId); continue; } if (allRanks) { if (!spellInfo->IsRanked()) - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc` with all ranks, but spell has no ranks.", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc` with all ranks, but spell has no ranks.", spellId); if (spellInfo->GetFirstRankSpell()->Id != uint32(spellId)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc` is not first rank of spell.", spellId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc` is not the first rank of the spell.", spellId); continue; } } SpellProcEntry baseProcEntry; - baseProcEntry.schoolMask = fields[1].GetInt8(); - baseProcEntry.spellFamilyName = fields[2].GetUInt16(); - baseProcEntry.spellFamilyMask[0] = fields[3].GetUInt32(); - baseProcEntry.spellFamilyMask[1] = fields[4].GetUInt32(); - baseProcEntry.spellFamilyMask[2] = fields[5].GetUInt32(); - baseProcEntry.typeMask = fields[6].GetUInt32(); - baseProcEntry.spellTypeMask = fields[7].GetUInt32(); - baseProcEntry.spellPhaseMask = fields[8].GetUInt32(); - baseProcEntry.hitMask = fields[9].GetUInt32(); - baseProcEntry.attributesMask = fields[10].GetUInt32(); - baseProcEntry.ratePerMinute = fields[11].GetFloat(); - baseProcEntry.chance = fields[12].GetFloat(); - float cooldown = fields[13].GetFloat(); - baseProcEntry.cooldown = uint32(cooldown); - baseProcEntry.charges = fields[14].GetUInt32(); + baseProcEntry.SchoolMask = fields[1].GetInt8(); + baseProcEntry.SpellFamilyName = fields[2].GetUInt16(); + baseProcEntry.SpellFamilyMask[0] = fields[3].GetUInt32(); + baseProcEntry.SpellFamilyMask[1] = fields[4].GetUInt32(); + baseProcEntry.SpellFamilyMask[2] = fields[5].GetUInt32(); + baseProcEntry.ProcFlags = fields[6].GetUInt32(); + baseProcEntry.SpellTypeMask = fields[7].GetUInt32(); + baseProcEntry.SpellPhaseMask = fields[8].GetUInt32(); + baseProcEntry.HitMask = fields[9].GetUInt32(); + baseProcEntry.AttributesMask = fields[10].GetUInt32(); + baseProcEntry.ProcsPerMinute = fields[11].GetFloat(); + baseProcEntry.Chance = fields[12].GetFloat(); + baseProcEntry.Cooldown = Milliseconds(fields[13].GetUInt32()); + baseProcEntry.Charges = fields[14].GetUInt8(); while (spellInfo) { if (mSpellProcMap.find(spellInfo->Id) != mSpellProcMap.end()) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_proc` already has its first rank in table.", spellInfo->Id); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_proc` already has its first rank in the table.", spellInfo->Id); break; } SpellProcEntry procEntry = SpellProcEntry(baseProcEntry); // take defaults from dbcs - if (!procEntry.typeMask) - procEntry.typeMask = spellInfo->ProcFlags; - if (!procEntry.charges) - procEntry.charges = spellInfo->ProcCharges; - if (!procEntry.chance && !procEntry.ratePerMinute) - procEntry.chance = float(spellInfo->ProcChance); + if (!procEntry.ProcFlags) + procEntry.ProcFlags = spellInfo->ProcFlags; + if (!procEntry.Charges) + procEntry.Charges = spellInfo->ProcCharges; + if (!procEntry.Chance && !procEntry.ProcsPerMinute) + procEntry.Chance = float(spellInfo->ProcChance); // validate data - if (procEntry.schoolMask & ~SPELL_SCHOOL_MASK_ALL) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `schoolMask` set: %u", spellInfo->Id, procEntry.schoolMask); - if (procEntry.spellFamilyName && (procEntry.spellFamilyName < 3 || procEntry.spellFamilyName > 17 || procEntry.spellFamilyName == 14 || procEntry.spellFamilyName == 16)) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `spellFamilyName` set: %u", spellInfo->Id, procEntry.spellFamilyName); - if (procEntry.chance < 0) + if (procEntry.SchoolMask & ~SPELL_SCHOOL_MASK_ALL) + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `SchoolMask` set: %u", spellInfo->Id, procEntry.SchoolMask); + if (procEntry.SpellFamilyName && (procEntry.SpellFamilyName < 3 || procEntry.SpellFamilyName > 17 || procEntry.SpellFamilyName == 14 || procEntry.SpellFamilyName == 16)) + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `SpellFamilyName` set: %u", spellInfo->Id, procEntry.SpellFamilyName); + if (procEntry.Chance < 0) { - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has negative value in `chance` field", spellInfo->Id); - procEntry.chance = 0; + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has negative value in the `Chance` field", spellInfo->Id); + procEntry.Chance = 0; } - if (procEntry.ratePerMinute < 0) + if (procEntry.ProcsPerMinute < 0) { - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has negative value in `ratePerMinute` field", spellInfo->Id); - procEntry.ratePerMinute = 0; + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has negative value in the `ProcsPerMinute` field", spellInfo->Id); + procEntry.ProcsPerMinute = 0; } - if (cooldown < 0) - { - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has negative value in `cooldown` field", spellInfo->Id); - procEntry.cooldown = 0; - } - if (procEntry.chance == 0 && procEntry.ratePerMinute == 0) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u doesn't have `chance` and `ratePerMinute` values defined, proc will not be triggered", spellInfo->Id); - if (procEntry.charges > 99) - { - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has too big value in `charges` field", spellInfo->Id); - procEntry.charges = 99; - } - if (!procEntry.typeMask) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u doesn't have `typeMask` value defined, proc will not be triggered", spellInfo->Id); - if (procEntry.spellTypeMask & ~PROC_SPELL_TYPE_MASK_ALL) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `spellTypeMask` set: %u", spellInfo->Id, procEntry.spellTypeMask); - if (procEntry.spellTypeMask && !(procEntry.typeMask & (SPELL_PROC_FLAG_MASK | PERIODIC_PROC_FLAG_MASK))) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has `spellTypeMask` value defined, but it won't be used for defined `typeMask` value", spellInfo->Id); - if (!procEntry.spellPhaseMask && procEntry.typeMask & REQ_SPELL_PHASE_PROC_FLAG_MASK) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u doesn't have `spellPhaseMask` value defined, but it's required for defined `typeMask` value, proc will not be triggered", spellInfo->Id); - if (procEntry.spellPhaseMask & ~PROC_SPELL_PHASE_MASK_ALL) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `spellPhaseMask` set: %u", spellInfo->Id, procEntry.spellPhaseMask); - if (procEntry.spellPhaseMask && !(procEntry.typeMask & REQ_SPELL_PHASE_PROC_FLAG_MASK)) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has `spellPhaseMask` value defined, but it won't be used for defined `typeMask` value", spellInfo->Id); - if (procEntry.hitMask & ~PROC_HIT_MASK_ALL) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `hitMask` set: %u", spellInfo->Id, procEntry.hitMask); - if (procEntry.hitMask && !(procEntry.typeMask & TAKEN_HIT_PROC_FLAG_MASK || (procEntry.typeMask & DONE_HIT_PROC_FLAG_MASK && (!procEntry.spellPhaseMask || procEntry.spellPhaseMask & (PROC_SPELL_PHASE_HIT | PROC_SPELL_PHASE_FINISH))))) - TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has `hitMask` value defined, but it won't be used for defined `typeMask` and `spellPhaseMask` values", spellInfo->Id); + if (procEntry.Chance == 0 && procEntry.ProcsPerMinute == 0) + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u doesn't have any `Chance` and `ProcsPerMinute` values defined, proc will not be triggered", spellInfo->Id); + if (!procEntry.ProcFlags) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u doesn't have any `ProcFlags` value defined, proc will not be triggered.", spellInfo->Id); + if (procEntry.SpellTypeMask & ~PROC_SPELL_TYPE_MASK_ALL) + TC_LOG_ERROR("sql.sql", "`spell_proc` table entry for spellId %u has wrong `SpellTypeMask` set: %u", spellInfo->Id, procEntry.SpellTypeMask); + if (procEntry.SpellTypeMask && !(procEntry.ProcFlags & (SPELL_PROC_FLAG_MASK | PERIODIC_PROC_FLAG_MASK))) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u has `SpellTypeMask` value defined, but it will not be used for the defined `ProcFlags` value.", spellInfo->Id); + if (!procEntry.SpellPhaseMask && procEntry.ProcFlags & REQ_SPELL_PHASE_PROC_FLAG_MASK) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u doesn't have any `SpellPhaseMask` value defined, but it is required for the defined `ProcFlags` value. Proc will not be triggered.", spellInfo->Id); + if (procEntry.SpellPhaseMask & ~PROC_SPELL_PHASE_MASK_ALL) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u has wrong `SpellPhaseMask` set: %u", spellInfo->Id, procEntry.SpellPhaseMask); + if (procEntry.SpellPhaseMask && !(procEntry.ProcFlags & REQ_SPELL_PHASE_PROC_FLAG_MASK)) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u has a `SpellPhaseMask` value defined, but it will not be used for the defined `ProcFlags` value.", spellInfo->Id); + if (procEntry.HitMask & ~PROC_HIT_MASK_ALL) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u has wrong `HitMask` set: %u", spellInfo->Id, procEntry.HitMask); + if (procEntry.HitMask && !(procEntry.ProcFlags & TAKEN_HIT_PROC_FLAG_MASK || (procEntry.ProcFlags & DONE_HIT_PROC_FLAG_MASK && (!procEntry.SpellPhaseMask || procEntry.SpellPhaseMask & (PROC_SPELL_PHASE_HIT | PROC_SPELL_PHASE_FINISH))))) + TC_LOG_ERROR("sql.sql", "The `spell_proc` table entry for spellId %u has `HitMask` value defined, but it will not be used for defined `ProcFlags` and `SpellPhaseMask` values.", spellInfo->Id); mSpellProcMap[spellInfo->Id] = procEntry; @@ -2081,7 +2079,7 @@ void SpellMgr::LoadSpellBonusess() SpellInfo const* spell = GetSpellInfo(entry); if (!spell) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_bonus_data` does not exist", entry); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_bonus_data` does not exist.", entry); continue; } @@ -2120,7 +2118,7 @@ void SpellMgr::LoadSpellThreats() if (!GetSpellInfo(entry)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_threat` does not exist", entry); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_threat` does not exist.", entry); continue; } @@ -2189,21 +2187,21 @@ void SpellMgr::LoadSpellPetAuras() SpellInfo const* spellInfo = GetSpellInfo(spell); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_pet_auras` does not exist", spell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_pet_auras` does not exist.", spell); continue; } if (spellInfo->Effects[eff].Effect != SPELL_EFFECT_DUMMY && (spellInfo->Effects[eff].Effect != SPELL_EFFECT_APPLY_AURA || spellInfo->Effects[eff].ApplyAuraName != SPELL_AURA_DUMMY)) { - TC_LOG_ERROR("spells", "Spell %u listed in `spell_pet_auras` does not have dummy aura or dummy effect", spell); + TC_LOG_ERROR("spells", "The spell %u listed in `spell_pet_auras` does not have any dummy aura or dummy effect.", spell); continue; } SpellInfo const* spellInfo2 = GetSpellInfo(aura); if (!spellInfo2) { - TC_LOG_ERROR("sql.sql", "Aura %u listed in `spell_pet_auras` does not exist", aura); + TC_LOG_ERROR("sql.sql", "The aura %u listed in `spell_pet_auras` does not exist.", aura); continue; } @@ -2281,7 +2279,7 @@ void SpellMgr::LoadSpellEnchantProcData() SpellItemEnchantmentEntry const* ench = sSpellItemEnchantmentStore.LookupEntry(enchantId); if (!ench) { - TC_LOG_ERROR("sql.sql", "Enchancment %u listed in `spell_enchant_proc_data` does not exist", enchantId); + TC_LOG_ERROR("sql.sql", "The enchancment %u listed in `spell_enchant_proc_data` does not exist.", enchantId); continue; } @@ -2325,7 +2323,7 @@ void SpellMgr::LoadSpellLinked() SpellInfo const* spellInfo = GetSpellInfo(abs(trigger)); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_linked_spell` does not exist", abs(trigger)); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_linked_spell` does not exist.", abs(trigger)); continue; } @@ -2333,13 +2331,13 @@ void SpellMgr::LoadSpellLinked() for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (spellInfo->Effects[j].CalcValue() == abs(effect)) - TC_LOG_ERROR("sql.sql", "Spell %u Effect: %u listed in `spell_linked_spell` has same bp%u like effect (possible hack)", abs(trigger), abs(effect), j); + TC_LOG_ERROR("sql.sql", "The spell %u Effect: %u listed in `spell_linked_spell` has same bp%u like effect (possible hack).", abs(trigger), abs(effect), j); } spellInfo = GetSpellInfo(abs(effect)); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_linked_spell` does not exist", abs(effect)); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_linked_spell` does not exist.", abs(effect)); continue; } @@ -2584,7 +2582,7 @@ void SpellMgr::LoadSpellAreas() } else { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` does not exist", spell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` does not exist", spell); continue; } @@ -2613,20 +2611,20 @@ void SpellMgr::LoadSpellAreas() if (!ok) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` already listed with similar requirements.", spell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` is already listed with similar requirements.", spell); continue; } } if (spellArea.areaId && !sAreaTableStore.LookupEntry(spellArea.areaId)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong area (%u) requirement", spell, spellArea.areaId); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has a wrong area (%u) requirement.", spell, spellArea.areaId); continue; } if (spellArea.questStart && !sObjectMgr->GetQuestTemplate(spellArea.questStart)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong start quest (%u) requirement", spell, spellArea.questStart); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has a wrong start quest (%u) requirement.", spell, spellArea.questStart); continue; } @@ -2634,7 +2632,7 @@ void SpellMgr::LoadSpellAreas() { if (!sObjectMgr->GetQuestTemplate(spellArea.questEnd)) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong end quest (%u) requirement", spell, spellArea.questEnd); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has a wrong ending quest (%u) requirement.", spell, spellArea.questEnd); continue; } } @@ -2644,13 +2642,13 @@ void SpellMgr::LoadSpellAreas() SpellInfo const* spellInfo = GetSpellInfo(abs(spellArea.auraSpell)); if (!spellInfo) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong aura spell (%u) requirement", spell, abs(spellArea.auraSpell)); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has wrong aura spell (%u) requirement", spell, abs(spellArea.auraSpell)); continue; } if (uint32(abs(spellArea.auraSpell)) == spellArea.spellId) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have aura spell (%u) requirement for itself", spell, abs(spellArea.auraSpell)); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has aura spell (%u) requirement for itself", spell, abs(spellArea.auraSpell)); continue; } @@ -2670,7 +2668,7 @@ void SpellMgr::LoadSpellAreas() if (chain) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell, spellArea.auraSpell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has the aura spell (%u) requirement that it autocasts itself from the aura.", spell, spellArea.auraSpell); continue; } @@ -2686,7 +2684,7 @@ void SpellMgr::LoadSpellAreas() if (chain) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have aura spell (%u) requirement that itself autocast from aura", spell, spellArea.auraSpell); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has the aura spell (%u) requirement that the spell itself autocasts from the aura.", spell, spellArea.auraSpell); continue; } } @@ -2694,13 +2692,13 @@ void SpellMgr::LoadSpellAreas() if (spellArea.raceMask && (spellArea.raceMask & RACEMASK_ALL_PLAYABLE) == 0) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong race mask (%u) requirement", spell, spellArea.raceMask); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has wrong race mask (%u) requirement.", spell, spellArea.raceMask); continue; } if (spellArea.gender != GENDER_NONE && spellArea.gender != GENDER_FEMALE && spellArea.gender != GENDER_MALE) { - TC_LOG_ERROR("sql.sql", "Spell %u listed in `spell_area` have wrong gender (%u) requirement", spell, spellArea.gender); + TC_LOG_ERROR("sql.sql", "The spell %u listed in `spell_area` has wrong gender (%u) requirement.", spell, spellArea.gender); continue; } @@ -3050,6 +3048,7 @@ void SpellMgr::LoadSpellInfoCorrections() case 48246: // Ball of Flame case 36327: // Shoot Arcane Explosion Arrow case 55479: // Force Obedience + case 28560: // Summon Blizzard (Sapphiron) spellInfo->MaxAffectedTargets = 1; break; case 36384: // Skartax Purple Beam @@ -3074,6 +3073,13 @@ void SpellMgr::LoadSpellInfoCorrections() case 53385: // Divine Storm (Damage) spellInfo->MaxAffectedTargets = 4; break; + case 53480: // Roar of Sacrifice + // missing spell effect 2 data, taken from 4.3.4 + spellInfo->Effects[EFFECT_1].Effect = SPELL_EFFECT_APPLY_AURA; + spellInfo->Effects[EFFECT_1].ApplyAuraName = SPELL_AURA_DUMMY; + spellInfo->Effects[EFFECT_1].MiscValue = 127; + spellInfo->Effects[EFFECT_1].TargetA = SpellImplicitTargetInfo(TARGET_UNIT_TARGET_ALLY); + break; case 42005: // Bloodboil case 38296: // Spitfire Totem case 37676: // Insidious Whisper @@ -3235,6 +3241,8 @@ void SpellMgr::LoadSpellInfoCorrections() spellInfo->AttributesEx4 = 0; break; case 8145: // Tremor Totem (instant pulse) + spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; + /*no break*/ case 6474: // Earthbind Totem (instant pulse) spellInfo->AttributesEx5 |= SPELL_ATTR5_START_PERIODIC_AT_APPLY; break; @@ -3337,6 +3345,24 @@ void SpellMgr::LoadSpellInfoCorrections() //! HACK: This spell break quest complete for alliance and on retail not used °_O spellInfo->Effects[EFFECT_0].Effect = 0; break; + case 47476: // Deathknight - Strangulate + case 15487: // Priest - Silence + case 5211: // Druid - Bash - R1 + case 6798: // Druid - Bash - R2 + case 8983: // Druid - Bash - R3 + spellInfo->AttributesEx7 |= SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER; + break; + case 42490: // Energized! + case 42492: // Cast Energized + spellInfo->AttributesEx |= SPELL_ATTR1_NO_THREAT; + break; + case 46842: // Flame Ring + case 46836: // Flame Patch + spellInfo->Effects[EFFECT_0].TargetA = SpellImplicitTargetInfo(); + break; + case 29726: // Test Ribbon Pole Channel + spellInfo->InterruptFlags &= ~AURA_INTERRUPT_FLAG_CAST; + break; // VIOLET HOLD SPELLS // case 54258: // Water Globule (Ichoron) @@ -3695,9 +3721,17 @@ void SpellMgr::LoadSpellInfoCorrections() spellInfo->AttributesEx6 |= SPELL_ATTR6_CAN_TARGET_INVISIBLE; spellInfo->AttributesEx2 |= SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS; break; - case 75888: // Awaken Flames - case 75889: // Awaken Flames - spellInfo->AttributesEx |= SPELL_ATTR1_CANT_TARGET_SELF; + case 75875: // Combustion and Consumption Heroic versions lacks radius data + spellInfo->Effects[EFFECT_0].Mechanic = MECHANIC_NONE; + spellInfo->Effects[EFFECT_1].Mechanic = MECHANIC_SNARE; + spellInfo->Effects[EFFECT_1].RadiusEntry = sSpellRadiusStore.LookupEntry(EFFECT_RADIUS_6_YARDS); + break; + case 75884: + spellInfo->Effects[EFFECT_0].RadiusEntry = sSpellRadiusStore.LookupEntry(EFFECT_RADIUS_6_YARDS); + // No break + case 75883: + case 75876: + spellInfo->Effects[EFFECT_1].RadiusEntry = sSpellRadiusStore.LookupEntry(EFFECT_RADIUS_6_YARDS); break; // ENDOF RUBY SANCTUM SPELLS // @@ -3746,12 +3780,6 @@ void SpellMgr::LoadSpellInfoCorrections() case 24314: // Threatening Gaze spellInfo->AuraInterruptFlags |= AURA_INTERRUPT_FLAG_CAST | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_JUMP; break; - case 45257: // Using Steam Tonk Controller - case 45440: // Steam Tonk Controller - case 60256: // Collect Sample - // Crashes client on pressing ESC - spellInfo->AttributesEx4 &= ~SPELL_ATTR4_CAN_CAST_WHILE_CASTING; - break; // ISLE OF CONQUEST SPELLS // case 66551: // Teleport diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index 651a8cde938..75da933636c 100644 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -266,7 +266,7 @@ enum ProcFlagsHit PROC_HIT_REFLECT = 0x0000800, PROC_HIT_INTERRUPT = 0x0001000, // (not used atm) PROC_HIT_FULL_BLOCK = 0x0002000, - PROC_HIT_MASK_ALL = 0x2FFF + PROC_HIT_MASK_ALL = 0x0002FFF }; enum ProcAttributes @@ -290,18 +290,18 @@ typedef std::unordered_map<uint32, SpellProcEventEntry> SpellProcEventMap; struct SpellProcEntry { - uint32 schoolMask; // if nonzero - bitmask for matching proc condition based on spell's school - uint32 spellFamilyName; // if nonzero - for matching proc condition based on candidate spell's SpellFamilyName - flag96 spellFamilyMask; // if nonzero - bitmask for matching proc condition based on candidate spell's SpellFamilyFlags - uint32 typeMask; // if nonzero - owerwrite procFlags field for given Spell.dbc entry, bitmask for matching proc condition, see enum ProcFlags - uint32 spellTypeMask; // if nonzero - bitmask for matching proc condition based on candidate spell's damage/heal effects, see enum ProcFlagsSpellType - uint32 spellPhaseMask; // if nonzero - bitmask for matching phase of a spellcast on which proc occurs, see enum ProcFlagsSpellPhase - uint32 hitMask; // if nonzero - bitmask for matching proc condition based on hit result, see enum ProcFlagsHit - uint32 attributesMask; // bitmask, see ProcAttributes - float ratePerMinute; // if nonzero - chance to proc is equal to value * aura caster's weapon speed / 60 - float chance; // if nonzero - owerwrite procChance field for given Spell.dbc entry, defines chance of proc to occur, not used if perMinuteRate set - uint32 cooldown; // if nonzero - cooldown in secs for aura proc, applied to aura - uint32 charges; // if nonzero - owerwrite procCharges field for given Spell.dbc entry, defines how many times proc can occur before aura remove, 0 - infinite + uint32 SchoolMask; // if nonzero - bitmask for matching proc condition based on spell's school + uint32 SpellFamilyName; // if nonzero - for matching proc condition based on candidate spell's SpellFamilyName + flag96 SpellFamilyMask; // if nonzero - bitmask for matching proc condition based on candidate spell's SpellFamilyFlags + uint32 ProcFlags; // if nonzero - owerwrite procFlags field for given Spell.dbc entry, bitmask for matching proc condition, see enum ProcFlags + uint32 SpellTypeMask; // if nonzero - bitmask for matching proc condition based on candidate spell's damage/heal effects, see enum ProcFlagsSpellType + uint32 SpellPhaseMask; // if nonzero - bitmask for matching phase of a spellcast on which proc occurs, see enum ProcFlagsSpellPhase + uint32 HitMask; // if nonzero - bitmask for matching proc condition based on hit result, see enum ProcFlagsHit + uint32 AttributesMask; // bitmask, see ProcAttributes + float ProcsPerMinute; // if nonzero - chance to proc is equal to value * aura caster's weapon speed / 60 + float Chance; // if nonzero - owerwrite procChance field for given Spell.dbc entry, defines chance of proc to occur, not used if ProcsPerMinute set + Milliseconds Cooldown; // if nonzero - cooldown in secs for aura proc, applied to aura + uint32 Charges; // if nonzero - owerwrite procCharges field for given Spell.dbc entry, defines how many times proc can occur before aura remove, 0 - infinite }; typedef std::unordered_map<uint32, SpellProcEntry> SpellProcMap; @@ -441,7 +441,7 @@ enum EffectRadiusIndex }; // Spell pet auras -class PetAura +class TC_GAME_API PetAura { private: typedef std::unordered_map<uint32, uint32> PetAuraMap; @@ -488,7 +488,7 @@ class PetAura }; typedef std::map<uint32, PetAura> SpellPetAuraMap; -struct SpellArea +struct TC_GAME_API SpellArea { uint32 spellId; uint32 areaId; // zone/subzone/or 0 is not limited to zone @@ -593,13 +593,13 @@ inline bool IsProfessionOrRidingSkill(uint32 skill) bool IsPartOfSkillLine(uint32 skillId, uint32 spellId); // spell diminishing returns -DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellInfo const* spellproto, bool triggered); -DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group); -DiminishingLevels GetDiminishingReturnsMaxLevel(DiminishingGroup group); -int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellInfo const* spellproto); -bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group); +TC_GAME_API DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellInfo const* spellproto, bool triggered); +TC_GAME_API DiminishingReturnsType GetDiminishingReturnsGroupType(DiminishingGroup group); +TC_GAME_API DiminishingLevels GetDiminishingReturnsMaxLevel(DiminishingGroup group); +TC_GAME_API int32 GetDiminishingReturnsLimitDuration(DiminishingGroup group, SpellInfo const* spellproto); +TC_GAME_API bool IsDiminishingReturnsGroupDurationLimited(DiminishingGroup group); -class SpellMgr +class TC_GAME_API SpellMgr { // Constructors private: @@ -608,11 +608,7 @@ class SpellMgr // Accessors (const or static functions) public: - static SpellMgr* instance() - { - static SpellMgr instance; - return &instance; - } + static SpellMgr* instance(); // Spell correctness for client using static bool IsSpellValid(SpellInfo const* spellInfo, Player* player = NULL, bool msg = true); @@ -696,7 +692,7 @@ class SpellMgr // SpellInfo object management SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : NULL; } // Use this only with 100% valid spellIds - SpellInfo const* EnsureSpellInfo(uint32 spellId) const + SpellInfo const* AssertSpellInfo(uint32 spellId) const { ASSERT(spellId < GetSpellInfoStoreSize()); SpellInfo const* spellInfo = mSpellInfoMap[spellId]; diff --git a/src/server/game/Spells/SpellScript.cpp b/src/server/game/Spells/SpellScript.cpp index 6876f8fa7ef..e2598386466 100644 --- a/src/server/game/Spells/SpellScript.cpp +++ b/src/server/game/Spells/SpellScript.cpp @@ -16,6 +16,7 @@ */ #include "Spell.h" +#include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellScript.h" #include "SpellMgr.h" @@ -50,6 +51,12 @@ void _SpellScript::_Init(std::string const* scriptname, uint32 spellId) m_currentScriptState = SPELL_SCRIPT_STATE_NONE; m_scriptName = scriptname; m_scriptSpellId = spellId; + +#ifdef TRINITY_API_USE_DYNAMIC_LINKING + // Acquire a strong reference to the binary code + // to keep it loaded until all spells are destroyed. + m_moduleReference = sScriptMgr->AcquireModuleReferenceOfScriptName(*scriptname); +#endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING } std::string const* _SpellScript::_GetScriptName() const diff --git a/src/server/game/Spells/SpellScript.h b/src/server/game/Spells/SpellScript.h index 77a993fffae..539bc54cc94 100644 --- a/src/server/game/Spells/SpellScript.h +++ b/src/server/game/Spells/SpellScript.h @@ -22,6 +22,7 @@ #include "SharedDefines.h" #include "SpellAuraDefines.h" #include "Spell.h" +#include "ScriptReloadMgr.h" #include <stack> class Unit; @@ -52,7 +53,7 @@ enum SpellScriptState #define SPELL_SCRIPT_STATE_END SPELL_SCRIPT_STATE_UNLOADING + 1 // helper class from which SpellScript and SpellAura derive, use these classes instead -class _SpellScript +class TC_GAME_API _SpellScript { // internal use classes & functions // DO NOT OVERRIDE THESE IN SCRIPTS @@ -68,7 +69,7 @@ class _SpellScript std::string const* _GetScriptName() const; protected: - class EffectHook + class TC_GAME_API EffectHook { public: EffectHook(uint8 _effIndex); @@ -82,7 +83,7 @@ class _SpellScript uint8 effIndex; }; - class EffectNameCheck + class TC_GAME_API EffectNameCheck { public: EffectNameCheck(uint16 _effName) { effName = _effName; } @@ -92,7 +93,7 @@ class _SpellScript uint16 effName; }; - class EffectAuraNameCheck + class TC_GAME_API EffectAuraNameCheck { public: EffectAuraNameCheck(uint16 _effAurName) { effAurName = _effAurName; } @@ -105,6 +106,16 @@ class _SpellScript uint8 m_currentScriptState; std::string const* m_scriptName; uint32 m_scriptSpellId; + + private: + +#ifdef TRINITY_API_USE_DYNAMIC_LINKING + + // Strong reference to keep the binary code loaded + std::shared_ptr<ModuleReference> m_moduleReference; + +#endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING + public: // // SpellScript/AuraScript interface base @@ -149,7 +160,7 @@ enum SpellScriptHookType #define HOOK_SPELL_END SPELL_SCRIPT_HOOK_CHECK_CAST + 1 #define HOOK_SPELL_COUNT HOOK_SPELL_END - HOOK_SPELL_START -class SpellScript : public _SpellScript +class TC_GAME_API SpellScript : public _SpellScript { // internal use classes & functions // DO NOT OVERRIDE THESE IN SCRIPTS @@ -165,7 +176,7 @@ class SpellScript : public _SpellScript SPELLSCRIPT_FUNCTION_TYPE_DEFINES(SpellScript) - class CastHandler + class TC_GAME_API CastHandler { public: CastHandler(SpellCastFnType _pCastHandlerScript); @@ -174,7 +185,7 @@ class SpellScript : public _SpellScript SpellCastFnType pCastHandlerScript; }; - class CheckCastHandler + class TC_GAME_API CheckCastHandler { public: CheckCastHandler(SpellCheckCastFnType checkCastHandlerScript); @@ -183,7 +194,7 @@ class SpellScript : public _SpellScript SpellCheckCastFnType _checkCastHandlerScript; }; - class EffectHandler : public _SpellScript::EffectNameCheck, public _SpellScript::EffectHook + class TC_GAME_API EffectHandler : public _SpellScript::EffectNameCheck, public _SpellScript::EffectHook { public: EffectHandler(SpellEffectFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -194,7 +205,7 @@ class SpellScript : public _SpellScript SpellEffectFnType pEffectHandlerScript; }; - class HitHandler + class TC_GAME_API HitHandler { public: HitHandler(SpellHitFnType _pHitHandlerScript); @@ -203,7 +214,7 @@ class SpellScript : public _SpellScript SpellHitFnType pHitHandlerScript; }; - class TargetHook : public _SpellScript::EffectHook + class TC_GAME_API TargetHook : public _SpellScript::EffectHook { public: TargetHook(uint8 _effectIndex, uint16 _targetType, bool _area, bool _dest); @@ -216,7 +227,7 @@ class SpellScript : public _SpellScript bool dest; }; - class ObjectAreaTargetSelectHandler : public TargetHook + class TC_GAME_API ObjectAreaTargetSelectHandler : public TargetHook { public: ObjectAreaTargetSelectHandler(SpellObjectAreaTargetSelectFnType _pObjectAreaTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); @@ -225,7 +236,7 @@ class SpellScript : public _SpellScript SpellObjectAreaTargetSelectFnType pObjectAreaTargetSelectHandlerScript; }; - class ObjectTargetSelectHandler : public TargetHook + class TC_GAME_API ObjectTargetSelectHandler : public TargetHook { public: ObjectTargetSelectHandler(SpellObjectTargetSelectFnType _pObjectTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); @@ -234,7 +245,7 @@ class SpellScript : public _SpellScript SpellObjectTargetSelectFnType pObjectTargetSelectHandlerScript; }; - class DestinationTargetSelectHandler : public TargetHook + class TC_GAME_API DestinationTargetSelectHandler : public TargetHook { public: DestinationTargetSelectHandler(SpellDestinationTargetSelectFnType _DestinationTargetSelectHandlerScript, uint8 _effIndex, uint16 _targetType); @@ -470,7 +481,7 @@ enum AuraScriptHookType #define HOOK_AURA_EFFECT_END HOOK_AURA_EFFECT_CALC_SPELLMOD + 1 #define HOOK_AURA_EFFECT_COUNT HOOK_AURA_EFFECT_END - HOOK_AURA_EFFECT_START */ -class AuraScript : public _SpellScript +class TC_GAME_API AuraScript : public _SpellScript { // internal use classes & functions // DO NOT OVERRIDE THESE IN SCRIPTS @@ -493,7 +504,7 @@ class AuraScript : public _SpellScript AURASCRIPT_FUNCTION_TYPE_DEFINES(AuraScript) - class CheckAreaTargetHandler + class TC_GAME_API CheckAreaTargetHandler { public: CheckAreaTargetHandler(AuraCheckAreaTargetFnType pHandlerScript); @@ -501,7 +512,7 @@ class AuraScript : public _SpellScript private: AuraCheckAreaTargetFnType pHandlerScript; }; - class AuraDispelHandler + class TC_GAME_API AuraDispelHandler { public: AuraDispelHandler(AuraDispelFnType pHandlerScript); @@ -509,14 +520,14 @@ class AuraScript : public _SpellScript private: AuraDispelFnType pHandlerScript; }; - class EffectBase : public _SpellScript::EffectAuraNameCheck, public _SpellScript::EffectHook + class TC_GAME_API EffectBase : public _SpellScript::EffectAuraNameCheck, public _SpellScript::EffectHook { public: EffectBase(uint8 _effIndex, uint16 _effName); std::string ToString(); bool CheckEffect(SpellInfo const* spellInfo, uint8 effIndex) override; }; - class EffectPeriodicHandler : public EffectBase + class TC_GAME_API EffectPeriodicHandler : public EffectBase { public: EffectPeriodicHandler(AuraEffectPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -524,7 +535,7 @@ class AuraScript : public _SpellScript private: AuraEffectPeriodicFnType pEffectHandlerScript; }; - class EffectUpdatePeriodicHandler : public EffectBase + class TC_GAME_API EffectUpdatePeriodicHandler : public EffectBase { public: EffectUpdatePeriodicHandler(AuraEffectUpdatePeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -532,7 +543,7 @@ class AuraScript : public _SpellScript private: AuraEffectUpdatePeriodicFnType pEffectHandlerScript; }; - class EffectCalcAmountHandler : public EffectBase + class TC_GAME_API EffectCalcAmountHandler : public EffectBase { public: EffectCalcAmountHandler(AuraEffectCalcAmountFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -540,7 +551,7 @@ class AuraScript : public _SpellScript private: AuraEffectCalcAmountFnType pEffectHandlerScript; }; - class EffectCalcPeriodicHandler : public EffectBase + class TC_GAME_API EffectCalcPeriodicHandler : public EffectBase { public: EffectCalcPeriodicHandler(AuraEffectCalcPeriodicFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -548,7 +559,7 @@ class AuraScript : public _SpellScript private: AuraEffectCalcPeriodicFnType pEffectHandlerScript; }; - class EffectCalcSpellModHandler : public EffectBase + class TC_GAME_API EffectCalcSpellModHandler : public EffectBase { public: EffectCalcSpellModHandler(AuraEffectCalcSpellModFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName); @@ -556,7 +567,7 @@ class AuraScript : public _SpellScript private: AuraEffectCalcSpellModFnType pEffectHandlerScript; }; - class EffectApplyHandler : public EffectBase + class TC_GAME_API EffectApplyHandler : public EffectBase { public: EffectApplyHandler(AuraEffectApplicationModeFnType _pEffectHandlerScript, uint8 _effIndex, uint16 _effName, AuraEffectHandleModes _mode); @@ -565,7 +576,7 @@ class AuraScript : public _SpellScript AuraEffectApplicationModeFnType pEffectHandlerScript; AuraEffectHandleModes mode; }; - class EffectAbsorbHandler : public EffectBase + class TC_GAME_API EffectAbsorbHandler : public EffectBase { public: EffectAbsorbHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); @@ -573,7 +584,7 @@ class AuraScript : public _SpellScript private: AuraEffectAbsorbFnType pEffectHandlerScript; }; - class EffectManaShieldHandler : public EffectBase + class TC_GAME_API EffectManaShieldHandler : public EffectBase { public: EffectManaShieldHandler(AuraEffectAbsorbFnType _pEffectHandlerScript, uint8 _effIndex); @@ -581,7 +592,7 @@ class AuraScript : public _SpellScript private: AuraEffectAbsorbFnType pEffectHandlerScript; }; - class EffectSplitHandler : public EffectBase + class TC_GAME_API EffectSplitHandler : public EffectBase { public: EffectSplitHandler(AuraEffectSplitFnType _pEffectHandlerScript, uint8 _effIndex); @@ -589,7 +600,7 @@ class AuraScript : public _SpellScript private: AuraEffectSplitFnType pEffectHandlerScript; }; - class CheckProcHandler + class TC_GAME_API CheckProcHandler { public: CheckProcHandler(AuraCheckProcFnType handlerScript); @@ -597,7 +608,7 @@ class AuraScript : public _SpellScript private: AuraCheckProcFnType _HandlerScript; }; - class AuraProcHandler + class TC_GAME_API AuraProcHandler { public: AuraProcHandler(AuraProcFnType handlerScript); @@ -605,7 +616,7 @@ class AuraScript : public _SpellScript private: AuraProcFnType _HandlerScript; }; - class EffectProcHandler : public EffectBase + class TC_GAME_API EffectProcHandler : public EffectBase { public: EffectProcHandler(AuraEffectProcFnType effectHandlerScript, uint8 effIndex, uint16 effName); @@ -645,7 +656,7 @@ class AuraScript : public _SpellScript AuraApplication const* m_auraApplication; bool m_defaultActionPrevented; - class ScriptStateStore + class TC_GAME_API ScriptStateStore { public: AuraApplication const* _auraApplication; diff --git a/src/server/game/Texts/CreatureTextMgr.cpp b/src/server/game/Texts/CreatureTextMgr.cpp index 499f0c9cbf0..d8df3310765 100644 --- a/src/server/game/Texts/CreatureTextMgr.cpp +++ b/src/server/game/Texts/CreatureTextMgr.cpp @@ -72,6 +72,12 @@ class PlayerTextBuilder WorldObject const* _target; }; +CreatureTextMgr* CreatureTextMgr::instance() +{ + static CreatureTextMgr instance; + return &instance; +} + void CreatureTextMgr::LoadCreatureTexts() { uint32 oldMSTime = getMSTime(); diff --git a/src/server/game/Texts/CreatureTextMgr.h b/src/server/game/Texts/CreatureTextMgr.h index 28fd98f21a8..d7953463a97 100644 --- a/src/server/game/Texts/CreatureTextMgr.h +++ b/src/server/game/Texts/CreatureTextMgr.h @@ -75,18 +75,14 @@ typedef std::unordered_map<uint32, CreatureTextHolder> CreatureTextMap; // a typedef std::map<CreatureTextId, CreatureTextLocale> LocaleCreatureTextMap; -class CreatureTextMgr +class TC_GAME_API CreatureTextMgr { private: CreatureTextMgr() { } ~CreatureTextMgr() { } public: - static CreatureTextMgr* instance() - { - static CreatureTextMgr instance; - return &instance; - } + static CreatureTextMgr* instance(); void LoadCreatureTexts(); void LoadCreatureTextLocales(); diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index 1cf68eec9c7..94e4427fe10 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -284,6 +284,12 @@ void TicketMgr::ResetTickets() CharacterDatabase.Execute(stmt); } +TicketMgr* TicketMgr::instance() +{ + static TicketMgr instance; + return &instance; +} + void TicketMgr::LoadTickets() { uint32 oldMSTime = getMSTime(); diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index 9cc1d20b122..ff2cd656dce 100644 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -84,7 +84,7 @@ enum TicketType TICKET_TYPE_CHARACTER_DELETED = 2, }; -class GmTicket +class TC_GAME_API GmTicket { public: GmTicket(); @@ -181,18 +181,14 @@ private: }; typedef std::map<uint32, GmTicket*> GmTicketList; -class TicketMgr +class TC_GAME_API TicketMgr { private: TicketMgr(); ~TicketMgr(); public: - static TicketMgr* instance() - { - static TicketMgr instance; - return &instance; - } + static TicketMgr* instance(); void LoadTickets(); void LoadSurveys(); diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.h b/src/server/game/Tools/CharacterDatabaseCleaner.h index ecbd6d0a790..f1e6900a6bb 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.h +++ b/src/server/game/Tools/CharacterDatabaseCleaner.h @@ -30,20 +30,20 @@ namespace CharacterDatabaseCleaner CLEANING_FLAG_QUESTSTATUS = 0x10 }; - void CleanDatabase(); + TC_GAME_API void CleanDatabase(); - void CheckUnique(const char* column, const char* table, bool (*check)(uint32)); + TC_GAME_API void CheckUnique(const char* column, const char* table, bool (*check)(uint32)); - bool AchievementProgressCheck(uint32 criteria); - bool SkillCheck(uint32 skill); - bool SpellCheck(uint32 spell_id); - bool TalentCheck(uint32 talent_id); + TC_GAME_API bool AchievementProgressCheck(uint32 criteria); + TC_GAME_API bool SkillCheck(uint32 skill); + TC_GAME_API bool SpellCheck(uint32 spell_id); + TC_GAME_API bool TalentCheck(uint32 talent_id); - void CleanCharacterAchievementProgress(); - void CleanCharacterSkills(); - void CleanCharacterSpell(); - void CleanCharacterTalent(); - void CleanCharacterQuestStatus(); + TC_GAME_API void CleanCharacterAchievementProgress(); + TC_GAME_API void CleanCharacterSkills(); + TC_GAME_API void CleanCharacterSpell(); + TC_GAME_API void CleanCharacterTalent(); + TC_GAME_API void CleanCharacterQuestStatus(); } #endif diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index 113fea2ea35..4c5ac1dab5e 100644 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -315,10 +315,10 @@ bool PlayerDumpWriter::DumpTable(std::string& dump, ObjectGuid::LowType guid, ch break; case DTT_CHARACTER: { - if (result->GetFieldCount() <= 68) // avoid crashes on next check + if (result->GetFieldCount() <= 73) // avoid crashes on next check TC_LOG_FATAL("misc", "PlayerDumpWriter::DumpTable - Trying to access non-existing or wrong positioned field (`deleteInfos_Account`) in `characters` table."); - if (result->Fetch()[68].GetUInt32()) // characters.deleteInfos_Account - if filled error + if (result->Fetch()[73].GetUInt32()) // characters.deleteInfos_Account - if filled error return false; break; } @@ -549,11 +549,11 @@ DumpReturn PlayerDumpReader::LoadDump(std::string const& file, uint32 account, s ROLLBACK(DUMP_FILE_BROKEN); const char null[5] = "NULL"; - if (!ChangeNth(line, 69, null)) // characters.deleteInfos_Account + if (!ChangeNth(line, 74, null)) // characters.deleteInfos_Account ROLLBACK(DUMP_FILE_BROKEN); - if (!ChangeNth(line, 70, null)) // characters.deleteInfos_Name + if (!ChangeNth(line, 75, null)) // characters.deleteInfos_Name ROLLBACK(DUMP_FILE_BROKEN); - if (!ChangeNth(line, 71, null)) // characters.deleteDate + if (!ChangeNth(line, 76, null)) // characters.deleteDate ROLLBACK(DUMP_FILE_BROKEN); break; } diff --git a/src/server/game/Tools/PlayerDump.h b/src/server/game/Tools/PlayerDump.h index 95d6ed2d04b..12cafc6ad48 100644 --- a/src/server/game/Tools/PlayerDump.h +++ b/src/server/game/Tools/PlayerDump.h @@ -62,7 +62,7 @@ enum DumpReturn DUMP_CHARACTER_DELETED }; -class PlayerDump +class TC_GAME_API PlayerDump { public: typedef std::set<ObjectGuid::LowType> DumpGuidSet; @@ -72,7 +72,7 @@ class PlayerDump PlayerDump() { } }; -class PlayerDumpWriter : public PlayerDump +class TC_GAME_API PlayerDumpWriter : public PlayerDump { public: PlayerDumpWriter() { } @@ -90,7 +90,7 @@ class PlayerDumpWriter : public PlayerDump DumpGuidSet items; }; -class PlayerDumpReader : public PlayerDump +class TC_GAME_API PlayerDumpReader : public PlayerDump { public: PlayerDumpReader() { } diff --git a/src/server/game/Warden/Warden.h b/src/server/game/Warden/Warden.h index 35ee18d4c02..b0aa496cbe8 100644 --- a/src/server/game/Warden/Warden.h +++ b/src/server/game/Warden/Warden.h @@ -92,7 +92,7 @@ struct ClientWardenModule class WorldSession; -class Warden +class TC_GAME_API Warden { friend class WardenWin; friend class WardenMac; diff --git a/src/server/game/Warden/WardenCheckMgr.cpp b/src/server/game/Warden/WardenCheckMgr.cpp index 5c4b0fc05b7..13ddae012fe 100644 --- a/src/server/game/Warden/WardenCheckMgr.cpp +++ b/src/server/game/Warden/WardenCheckMgr.cpp @@ -189,6 +189,12 @@ void WardenCheckMgr::LoadWardenOverrides() TC_LOG_INFO("server.loading", ">> Loaded %u warden action overrides.", count); } +WardenCheckMgr* WardenCheckMgr::instance() +{ + static WardenCheckMgr instance; + return &instance; +} + WardenCheck* WardenCheckMgr::GetWardenDataById(uint16 Id) { if (Id < CheckStore.size()) diff --git a/src/server/game/Warden/WardenCheckMgr.h b/src/server/game/Warden/WardenCheckMgr.h index 4107ccc3aff..7349fd5b589 100644 --- a/src/server/game/Warden/WardenCheckMgr.h +++ b/src/server/game/Warden/WardenCheckMgr.h @@ -48,18 +48,14 @@ struct WardenCheckResult BigNumber Result; // MEM_CHECK }; -class WardenCheckMgr +class TC_GAME_API WardenCheckMgr { private: WardenCheckMgr(); ~WardenCheckMgr(); public: - static WardenCheckMgr* instance() - { - static WardenCheckMgr instance; - return &instance; - } + static WardenCheckMgr* instance(); // We have a linear key without any gaps, so we use vector for fast access typedef std::vector<WardenCheck*> CheckContainer; diff --git a/src/server/game/Warden/WardenMac.h b/src/server/game/Warden/WardenMac.h index 26a2d86524e..c7435502f63 100644 --- a/src/server/game/Warden/WardenMac.h +++ b/src/server/game/Warden/WardenMac.h @@ -28,7 +28,7 @@ class WorldSession; class Warden; -class WardenMac : public Warden +class TC_GAME_API WardenMac : public Warden { public: WardenMac(); diff --git a/src/server/game/Warden/WardenWin.h b/src/server/game/Warden/WardenWin.h index 4bf1af77c47..b3e6d7c586c 100644 --- a/src/server/game/Warden/WardenWin.h +++ b/src/server/game/Warden/WardenWin.h @@ -62,7 +62,7 @@ struct WardenInitModuleRequest class WorldSession; class Warden; -class WardenWin : public Warden +class TC_GAME_API WardenWin : public Warden { public: WardenWin(); diff --git a/src/server/game/Weather/Weather.cpp b/src/server/game/Weather/Weather.cpp index f774916f4a5..7ef16e32031 100644 --- a/src/server/game/Weather/Weather.cpp +++ b/src/server/game/Weather/Weather.cpp @@ -152,7 +152,7 @@ bool Weather::ReGenerate() uint32 chance2 = chance1+ m_weatherChances->data[season].snowChance; uint32 chance3 = chance2+ m_weatherChances->data[season].stormChance; - uint32 rnd = urand(0, 99); + uint32 rnd = urand(1, 100); if (rnd <= chance1) m_type = WEATHER_TYPE_RAIN; else if (rnd <= chance2) diff --git a/src/server/game/Weather/Weather.h b/src/server/game/Weather/Weather.h index c1f029d6264..6a770615308 100644 --- a/src/server/game/Weather/Weather.h +++ b/src/server/game/Weather/Weather.h @@ -62,7 +62,7 @@ enum WeatherState }; /// Weather for one zone -class Weather +class TC_GAME_API Weather { public: diff --git a/src/server/game/Weather/WeatherMgr.h b/src/server/game/Weather/WeatherMgr.h index 97c541fd3c0..e3dd4ac9ec4 100644 --- a/src/server/game/Weather/WeatherMgr.h +++ b/src/server/game/Weather/WeatherMgr.h @@ -30,15 +30,15 @@ class Player; namespace WeatherMgr { - void LoadWeatherData(); + TC_GAME_API void LoadWeatherData(); - Weather* FindWeather(uint32 id); - Weather* AddWeather(uint32 zone_id); - void RemoveWeather(uint32 zone_id); + TC_GAME_API Weather* FindWeather(uint32 id); + TC_GAME_API Weather* AddWeather(uint32 zone_id); + TC_GAME_API void RemoveWeather(uint32 zone_id); - void SendFineWeatherUpdateToPlayer(Player* player); + TC_GAME_API void SendFineWeatherUpdateToPlayer(Player* player); - void Update(uint32 diff); + TC_GAME_API void Update(uint32 diff); } #endif diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 289a4d47666..19abfbe3152 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -38,6 +38,7 @@ #include "DatabaseEnv.h" #include "DisableMgr.h" #include "GameEventMgr.h" +#include "GameObjectModel.h" #include "GridNotifiersImpl.h" #include "GroupMgr.h" #include "GuildMgr.h" @@ -53,9 +54,11 @@ #include "PoolMgr.h" #include "GitRevision.h" #include "ScriptMgr.h" +#include "ScriptReloadMgr.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SmartAI.h" +#include "Metric.h" #include "TicketMgr.h" #include "TransportMgr.h" #include "Unit.h" @@ -64,19 +67,20 @@ #include "WaypointMovementGenerator.h" #include "WeatherMgr.h" #include "WorldSession.h" +#include "M2Stores.h" +TC_GAME_API std::atomic<bool> World::m_stopEvent(false); +TC_GAME_API uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE; -std::atomic<bool> World::m_stopEvent(false); -uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE; -std::atomic<uint32> World::m_worldLoopCounter(0); +TC_GAME_API std::atomic<uint32> World::m_worldLoopCounter(0); -float World::m_MaxVisibleDistanceOnContinents = DEFAULT_VISIBILITY_DISTANCE; -float World::m_MaxVisibleDistanceInInstances = DEFAULT_VISIBILITY_INSTANCE; -float World::m_MaxVisibleDistanceInBGArenas = DEFAULT_VISIBILITY_BGARENAS; +TC_GAME_API float World::m_MaxVisibleDistanceOnContinents = DEFAULT_VISIBILITY_DISTANCE; +TC_GAME_API float World::m_MaxVisibleDistanceInInstances = DEFAULT_VISIBILITY_INSTANCE; +TC_GAME_API float World::m_MaxVisibleDistanceInBGArenas = DEFAULT_VISIBILITY_BGARENAS; -int32 World::m_visibility_notify_periodOnContinents = DEFAULT_VISIBILITY_NOTIFY_PERIOD; -int32 World::m_visibility_notify_periodInInstances = DEFAULT_VISIBILITY_NOTIFY_PERIOD; -int32 World::m_visibility_notify_periodInBGArenas = DEFAULT_VISIBILITY_NOTIFY_PERIOD; +TC_GAME_API int32 World::m_visibility_notify_periodOnContinents = DEFAULT_VISIBILITY_NOTIFY_PERIOD; +TC_GAME_API int32 World::m_visibility_notify_periodInInstances = DEFAULT_VISIBILITY_NOTIFY_PERIOD; +TC_GAME_API int32 World::m_visibility_notify_periodInBGArenas = DEFAULT_VISIBILITY_NOTIFY_PERIOD; /// World constructor World::World() @@ -139,6 +143,12 @@ World::~World() /// @todo free addSessQueue } +World* World::instance() +{ + static World instance; + return &instance; +} + /// Find a player in a specified zone Player* World::FindPlayerInZone(uint32 zone) { @@ -387,6 +397,7 @@ void World::LoadConfigSettings(bool reload) return; } sLog->LoadFromConfig(); + sMetric->LoadFromConfigs(); } ///- Read the player limit and the Message of the day from the config file @@ -584,7 +595,10 @@ void World::LoadConfigSettings(bool reload) } m_int_configs[CONFIG_CHAT_CHANNEL_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Channel", 1); m_int_configs[CONFIG_CHAT_WHISPER_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Whisper", 1); + m_int_configs[CONFIG_CHAT_EMOTE_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Emote", 1); m_int_configs[CONFIG_CHAT_SAY_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Say", 1); + m_int_configs[CONFIG_CHAT_YELL_LEVEL_REQ] = sConfigMgr->GetIntDefault("ChatLevelReq.Yell", 1); + m_int_configs[CONFIG_PARTY_LEVEL_REQ] = sConfigMgr->GetIntDefault("PartyLevelReq", 1); m_int_configs[CONFIG_TRADE_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Trade", 1); m_int_configs[CONFIG_TICKET_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Ticket", 1); m_int_configs[CONFIG_AUCTION_LEVEL_REQ] = sConfigMgr->GetIntDefault("LevelReq.Auction", 1); @@ -592,6 +606,18 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_PRESERVE_CUSTOM_CHANNELS] = sConfigMgr->GetBoolDefault("PreserveCustomChannels", false); m_int_configs[CONFIG_PRESERVE_CUSTOM_CHANNEL_DURATION] = sConfigMgr->GetIntDefault("PreserveCustomChannelDuration", 14); m_bool_configs[CONFIG_GRID_UNLOAD] = sConfigMgr->GetBoolDefault("GridUnload", true); + m_bool_configs[CONFIG_BASEMAP_LOAD_GRIDS] = sConfigMgr->GetBoolDefault("BaseMapLoadAllGrids", false); + if (m_bool_configs[CONFIG_BASEMAP_LOAD_GRIDS] && m_bool_configs[CONFIG_GRID_UNLOAD]) + { + TC_LOG_ERROR("server.loading", "BaseMapLoadAllGrids enabled, but GridUnload also enabled. GridUnload must be disabled to enable base map pre-loading. Base map pre-loading disabled"); + m_bool_configs[CONFIG_BASEMAP_LOAD_GRIDS] = false; + } + m_bool_configs[CONFIG_INSTANCEMAP_LOAD_GRIDS] = sConfigMgr->GetBoolDefault("InstanceMapLoadAllGrids", false); + if (m_bool_configs[CONFIG_INSTANCEMAP_LOAD_GRIDS] && m_bool_configs[CONFIG_GRID_UNLOAD]) + { + TC_LOG_ERROR("server.loading", "InstanceMapLoadAllGrids enabled, but GridUnload also enabled. GridUnload must be disabled to enable instance map pre-loading. Instance map pre-loading disabled"); + m_bool_configs[CONFIG_INSTANCEMAP_LOAD_GRIDS] = false; + } m_int_configs[CONFIG_INTERVAL_SAVE] = sConfigMgr->GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILLISECONDS); m_int_configs[CONFIG_INTERVAL_DISCONNECT_TOLERANCE] = sConfigMgr->GetIntDefault("DisconnectToleranceInterval", 0); m_bool_configs[CONFIG_STATS_SAVE_ONLY_ON_LOGOUT] = sConfigMgr->GetBoolDefault("PlayerSave.Stats.SaveOnlyOnLogout", true); @@ -638,9 +664,8 @@ void World::LoadConfigSettings(bool reload) m_float_configs[CONFIG_GROUP_XP_DISTANCE] = sConfigMgr->GetFloatDefault("MaxGroupXPDistance", 74.0f); m_float_configs[CONFIG_MAX_RECRUIT_A_FRIEND_DISTANCE] = sConfigMgr->GetFloatDefault("MaxRecruitAFriendBonusDistance", 100.0f); - /// @todo Add MonsterSight and GuarderSight (with meaning) in worldserver.conf or put them as define + /// @todo Add MonsterSight (with meaning) in worldserver.conf or put them as define m_float_configs[CONFIG_SIGHT_MONSTER] = sConfigMgr->GetFloatDefault("MonsterSight", 50.0f); - m_float_configs[CONFIG_SIGHT_GUARDER] = sConfigMgr->GetFloatDefault("GuarderSight", 50.0f); if (reload) { @@ -879,6 +904,7 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_ALLOW_GM_GROUP] = sConfigMgr->GetBoolDefault("GM.AllowInvite", false); m_bool_configs[CONFIG_GM_LOWER_SECURITY] = sConfigMgr->GetBoolDefault("GM.LowerSecurity", false); m_float_configs[CONFIG_CHANCE_OF_GM_SURVEY] = sConfigMgr->GetFloatDefault("GM.TicketSystem.ChanceOfGMSurvey", 50.0f); + m_int_configs[CONFIG_FORCE_SHUTDOWN_THRESHOLD] = sConfigMgr->GetIntDefault("GM.ForceShutdownThreshold", 30); m_int_configs[CONFIG_GROUP_VISIBILITY] = sConfigMgr->GetIntDefault("Visibility.GroupMode", 1); @@ -1003,7 +1029,7 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_DETECT_POS_COLLISION] = sConfigMgr->GetBoolDefault("DetectPosCollision", true); m_bool_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfigMgr->GetBoolDefault("Channel.RestrictedLfg", true); - m_bool_configs[CONFIG_TALENTS_INSPECTING] = sConfigMgr->GetBoolDefault("TalentsInspecting", true); + m_int_configs[CONFIG_TALENTS_INSPECTING] = sConfigMgr->GetIntDefault("TalentsInspecting", 1); m_bool_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfigMgr->GetBoolDefault("ChatFakeMessagePreventing", false); m_int_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY] = sConfigMgr->GetIntDefault("ChatStrictLinkChecking.Severity", 0); m_int_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_KICK] = sConfigMgr->GetIntDefault("ChatStrictLinkChecking.Kick", 0); @@ -1037,6 +1063,17 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfigMgr->GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false); m_bool_configs[CONFIG_BATTLEGROUND_STORE_STATISTICS_ENABLE] = sConfigMgr->GetBoolDefault("Battleground.StoreStatistics.Enable", false); m_bool_configs[CONFIG_BATTLEGROUND_TRACK_DESERTERS] = sConfigMgr->GetBoolDefault("Battleground.TrackDeserters.Enable", false); + m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = sConfigMgr->GetIntDefault("Battleground.ReportAFK", 3); + if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] < 1) + { + TC_LOG_ERROR("server.loading", "Battleground.ReportAFK (%d) must be >0. Using 3 instead.", m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK]); + m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = 3; + } + if (m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] > 9) + { + TC_LOG_ERROR("server.loading", "Battleground.ReportAFK (%d) must be <10. Using 3 instead.", m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK]); + m_int_configs[CONFIG_BATTLEGROUND_REPORT_AFK] = 3; + } m_int_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfigMgr->GetIntDefault ("Battleground.InvitationType", 0); m_int_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfigMgr->GetIntDefault ("Battleground.PrematureFinishTimer", 5 * MINUTE * IN_MILLISECONDS); m_int_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfigMgr->GetIntDefault ("Battleground.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILLISECONDS); @@ -1047,7 +1084,6 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfigMgr->GetBoolDefault("Arena.AutoDistributePoints", false); m_int_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfigMgr->GetIntDefault ("Arena.AutoDistributeInterval", 7); m_bool_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfigMgr->GetBoolDefault("Arena.QueueAnnouncer.Enable", false); - m_bool_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_PLAYERONLY] = sConfigMgr->GetBoolDefault("Arena.QueueAnnouncer.PlayerOnly", false); m_int_configs[CONFIG_ARENA_SEASON_ID] = sConfigMgr->GetIntDefault ("Arena.ArenaSeason.ID", 1); m_int_configs[CONFIG_ARENA_START_RATING] = sConfigMgr->GetIntDefault ("Arena.ArenaStartRating", 0); m_int_configs[CONFIG_ARENA_START_PERSONAL_RATING] = sConfigMgr->GetIntDefault ("Arena.ArenaStartPersonalRating", 1000); @@ -1062,6 +1098,7 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN] = sConfigMgr->GetBoolDefault("OffhandCheckAtSpellUnlearn", true); m_int_configs[CONFIG_CREATURE_PICKPOCKET_REFILL] = sConfigMgr->GetIntDefault("Creature.PickPocketRefillDelay", 10 * MINUTE); + m_int_configs[CONFIG_CREATURE_STOP_FOR_PLAYER] = sConfigMgr->GetIntDefault("Creature.MovingStopTimeForPlayer", 3 * MINUTE * IN_MILLISECONDS); if (int32 clientCacheId = sConfigMgr->GetIntDefault("ClientCacheVersion", 0)) { @@ -1300,13 +1337,22 @@ void World::LoadConfigSettings(bool reload) m_bool_configs[CONFIG_CALCULATE_CREATURE_ZONE_AREA_DATA] = sConfigMgr->GetBoolDefault("Calculate.Creature.Zone.Area.Data", false); m_bool_configs[CONFIG_CALCULATE_GAMEOBJECT_ZONE_AREA_DATA] = sConfigMgr->GetBoolDefault("Calculate.Gameoject.Zone.Area.Data", false); + // HotSwap + m_bool_configs[CONFIG_HOTSWAP_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.Enabled", true); + m_bool_configs[CONFIG_HOTSWAP_RECOMPILER_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.EnableReCompiler", true); + m_bool_configs[CONFIG_HOTSWAP_EARLY_TERMINATION_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.EnableEarlyTermination", true); + m_bool_configs[CONFIG_HOTSWAP_BUILD_FILE_RECREATION_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.EnableBuildFileRecreation", true); + m_bool_configs[CONFIG_HOTSWAP_INSTALL_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.EnableInstall", true); + m_bool_configs[CONFIG_HOTSWAP_PREFIX_CORRECTION_ENABLED] = sConfigMgr->GetBoolDefault("HotSwap.EnablePrefixCorrection", true); + + // prevent character rename on character customization + m_bool_configs[CONFIG_PREVENT_RENAME_CUSTOMIZATION] = sConfigMgr->GetBoolDefault("PreventRenameCharacterOnCustomization", false); + // call ScriptMgr if we're reloading the configuration if (reload) sScriptMgr->OnConfigLoad(reload); } -extern void LoadGameObjectModelList(std::string const& dataPath); - /// Initialize the World void World::SetInitialWorldSettings() { @@ -1369,13 +1415,16 @@ void World::SetInitialWorldSettings() uint32 server_type = IsFFAPvPRealm() ? uint32(REALM_TYPE_PVP) : getIntConfig(CONFIG_GAME_TYPE); uint32 realm_zone = getIntConfig(CONFIG_REALM_ZONE); - LoginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID); // One-time query + LoginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realm.Id.Realm); // One-time query ///- Load the DBC files TC_LOG_INFO("server.loading", "Initialize data stores..."); LoadDBCStores(m_dataPath); DetectDBCLang(); + // Load cinematic cameras + LoadM2Cameras(m_dataPath); + std::vector<uint32> mapIds; for (uint32 mapId = 0; mapId < sMapStore.GetNumRows(); mapId++) if (sMapStore.LookupEntry(mapId)) @@ -1790,7 +1839,7 @@ void World::SetInitialWorldSettings() m_startTime = m_gameTime; LoginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, uptime, revision) VALUES(%u, %u, 0, '%s')", - realmID, uint32(m_startTime), GitRevision::GetFullVersion()); // One-time query + realm.Id.Realm, uint32(m_startTime), GitRevision::GetFullVersion()); // One-time query m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILLISECONDS); m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILLISECONDS); @@ -1809,6 +1858,8 @@ void World::SetInitialWorldSettings() m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE*IN_MILLISECONDS); // Mysql ping time in minutes + m_timers[WUPDATE_CHECK_FILECHANGES].SetInterval(500); + //to set mailtimer to return mails every day between 4 and 5 am //mailtimer is increased when updating auctions //one second is 1000 -(tested on win system) @@ -1888,10 +1939,25 @@ void World::SetInitialWorldSettings() LoadCharacterInfoStore(); + // Preload all cells, if required for the base maps + if (sWorld->getBoolConfig(CONFIG_BASEMAP_LOAD_GRIDS)) + { + sMapMgr->DoForAllMaps([](Map* map) + { + if (!map->Instanceable()) + { + TC_LOG_INFO("server.loading", "Pre-loading base map data for map %u", map->GetId()); + map->LoadAllCells(); + } + }); + } + uint32 startupDuration = GetMSTimeDiffToNow(startupBegin); TC_LOG_INFO("server.worldserver", "World initialized in %u minutes %u seconds", (startupDuration / 60000), ((startupDuration % 60000) / 1000)); + TC_METRIC_EVENT("events", "World initialized", "World initialized in " + std::to_string(startupDuration / 60000) + " minutes " + std::to_string((startupDuration % 60000) / 1000) + " seconds"); + if (uint32 realmId = sConfigMgr->GetIntDefault("RealmID", 0)) // 0 reserved for auth sLog->SetRealmId(realmId); } @@ -2079,6 +2145,13 @@ void World::Update(uint32 diff) m_timers[WUPDATE_AHBOT].Reset(); } + /// <li> Handle file changes + if (m_timers[WUPDATE_CHECK_FILECHANGES].Passed()) + { + sScriptReloadMgr->Update(); + m_timers[WUPDATE_CHECK_FILECHANGES].Reset(); + } + /// <li> Handle session updates when the timer has passed ResetTimeDiffRecord(); UpdateSessions(diff); @@ -2103,7 +2176,7 @@ void World::Update(uint32 diff) stmt->setUInt32(0, tmpDiff); stmt->setUInt16(1, uint16(maxOnlinePlayers)); - stmt->setUInt32(2, realmID); + stmt->setUInt32(2, realm.Id.Realm); stmt->setUInt32(3, uint32(m_startTime)); LoginDatabase.Execute(stmt); @@ -2199,6 +2272,10 @@ void World::Update(uint32 diff) ProcessCliCommands(); sScriptMgr->OnWorldUpdate(diff); + + // Stats logger update + sMetric->Update(); + TC_METRIC_VALUE("update_time_diff", diff); } void World::ForceGameEventUpdate() @@ -2824,16 +2901,20 @@ void World::_UpdateRealmCharCount(PreparedQueryResult resultCharCount) uint32 accountId = fields[0].GetUInt32(); uint8 charCount = uint8(fields[1].GetUInt64()); + SQLTransaction trans = LoginDatabase.BeginTransaction(); + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM); stmt->setUInt32(0, accountId); - stmt->setUInt32(1, realmID); - LoginDatabase.Execute(stmt); + stmt->setUInt32(1, realm.Id.Realm); + trans->Append(stmt); stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_REALM_CHARACTERS); stmt->setUInt8(0, charCount); stmt->setUInt32(1, accountId); - stmt->setUInt32(2, realmID); - LoginDatabase.Execute(stmt); + stmt->setUInt32(2, realm.Id.Realm); + trans->Append(stmt); + + LoginDatabase.CommitTransaction(trans); } } @@ -2960,7 +3041,7 @@ void World::ResetDailyQuests() void World::LoadDBAllowedSecurityLevel() { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL); - stmt->setInt32(0, int32(realmID)); + stmt->setInt32(0, int32(realm.Id.Realm)); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) @@ -3290,3 +3371,4 @@ void World::RemoveOldCorpses() m_timers[WUPDATE_CORPSES].SetCurrent(m_timers[WUPDATE_CORPSES].GetInterval()); } +Realm realm; diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index 00b244c9efb..5850063bdc8 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -28,7 +28,8 @@ #include "Timer.h" #include "SharedDefines.h" #include "QueryResult.h" -#include "Callback.h" +#include "QueryCallback.h" +#include "Realm/Realm.h" #include <atomic> #include <map> @@ -55,7 +56,8 @@ enum ServerMessageType enum ShutdownMask { SHUTDOWN_MASK_RESTART = 1, - SHUTDOWN_MASK_IDLE = 2 + SHUTDOWN_MASK_IDLE = 2, + SHUTDOWN_MASK_FORCE = 4 }; enum ShutdownExitCode @@ -80,6 +82,7 @@ enum WorldTimers WUPDATE_DELETECHARS, WUPDATE_AHBOT, WUPDATE_PINGDB, + WUPDATE_CHECK_FILECHANGES, WUPDATE_COUNT }; @@ -113,7 +116,6 @@ enum WorldBoolConfigs CONFIG_QUEST_IGNORE_RAID, CONFIG_DETECT_POS_COLLISION, CONFIG_RESTRICTED_LFG_CHANNEL, - CONFIG_TALENTS_INSPECTING, CONFIG_CHAT_FAKE_MESSAGE_PREVENTING, CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP, CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE, @@ -129,7 +131,6 @@ enum WorldBoolConfigs CONFIG_BG_XP_FOR_KILL, CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS, CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE, - CONFIG_ARENA_QUEUE_ANNOUNCER_PLAYERONLY, CONFIG_ARENA_SEASON_IN_PROGRESS, CONFIG_ARENA_LOG_EXTENDED_INFO, CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN, @@ -166,6 +167,15 @@ enum WorldBoolConfigs CONFIG_CALCULATE_GAMEOBJECT_ZONE_AREA_DATA, CONFIG_RESET_DUEL_COOLDOWNS, CONFIG_RESET_DUEL_HEALTH_MANA, + CONFIG_BASEMAP_LOAD_GRIDS, + CONFIG_INSTANCEMAP_LOAD_GRIDS, + CONFIG_HOTSWAP_ENABLED, + CONFIG_HOTSWAP_RECOMPILER_ENABLED, + CONFIG_HOTSWAP_EARLY_TERMINATION_ENABLED, + CONFIG_HOTSWAP_BUILD_FILE_RECREATION_ENABLED, + CONFIG_HOTSWAP_INSTALL_ENABLED, + CONFIG_HOTSWAP_PREFIX_CORRECTION_ENABLED, + CONFIG_PREVENT_RENAME_CUSTOMIZATION, BOOL_CONFIG_VALUE_COUNT }; @@ -174,7 +184,6 @@ enum WorldFloatConfigs CONFIG_GROUP_XP_DISTANCE = 0, CONFIG_MAX_RECRUIT_A_FRIEND_DISTANCE, CONFIG_SIGHT_MONSTER, - CONFIG_SIGHT_GUARDER, CONFIG_LISTEN_RANGE_SAY, CONFIG_LISTEN_RANGE_TEXTEMOTE, CONFIG_LISTEN_RANGE_YELL, @@ -244,6 +253,7 @@ enum WorldIntConfigs CONFIG_GM_LEVEL_IN_GM_LIST, CONFIG_GM_LEVEL_IN_WHO_LIST, CONFIG_START_GM_LEVEL, + CONFIG_FORCE_SHUTDOWN_THRESHOLD, CONFIG_GROUP_VISIBILITY, CONFIG_MAIL_DELIVERY_DELAY, CONFIG_UPTIME_UPDATE, @@ -271,7 +281,10 @@ enum WorldIntConfigs CONFIG_CHAT_STRICT_LINK_CHECKING_KICK, CONFIG_CHAT_CHANNEL_LEVEL_REQ, CONFIG_CHAT_WHISPER_LEVEL_REQ, + CONFIG_CHAT_EMOTE_LEVEL_REQ, CONFIG_CHAT_SAY_LEVEL_REQ, + CONFIG_CHAT_YELL_LEVEL_REQ, + CONFIG_PARTY_LEVEL_REQ, CONFIG_TRADE_LEVEL_REQ, CONFIG_TICKET_LEVEL_REQ, CONFIG_AUCTION_LEVEL_REQ, @@ -287,6 +300,7 @@ enum WorldIntConfigs CONFIG_BATTLEGROUND_INVITATION_TYPE, CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER, CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH, + CONFIG_BATTLEGROUND_REPORT_AFK, CONFIG_ARENA_MAX_RATING_DIFFERENCE, CONFIG_ARENA_RATING_DISCARD_TIMER, CONFIG_ARENA_RATED_UPDATE_TIMER, @@ -349,6 +363,7 @@ enum WorldIntConfigs CONFIG_BG_REWARD_LOSER_HONOR_LAST, CONFIG_BIRTHDAY_TIME, CONFIG_CREATURE_PICKPOCKET_REFILL, + CONFIG_CREATURE_STOP_FOR_PLAYER, CONFIG_AHBOT_UPDATE_INTERVAL, CONFIG_CHARTER_COST_GUILD, CONFIG_CHARTER_COST_ARENA_2v2, @@ -358,6 +373,7 @@ enum WorldIntConfigs CONFIG_NO_GRAY_AGGRO_BELOW, CONFIG_AUCTION_GETALL_DELAY, CONFIG_AUCTION_SEARCH_DELAY, + CONFIG_TALENTS_INSPECTING, INT_CONFIG_VALUE_COUNT }; @@ -446,18 +462,6 @@ enum BillingPlanFlags SESSION_ENABLE_CAIS = 0x80 }; -/// Type of server, this is values from second column of Cfg_Configs.dbc -enum RealmType -{ - REALM_TYPE_NORMAL = 0, - REALM_TYPE_PVP = 1, - REALM_TYPE_NORMAL2 = 4, - REALM_TYPE_RP = 6, - REALM_TYPE_RPPVP = 8, - REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries - // replaced by REALM_PVP in realm list -}; - enum RealmZone { REALM_ZONE_UNKNOWN = 0, // any language @@ -546,14 +550,10 @@ struct CharacterInfo }; /// The World -class World +class TC_GAME_API World { public: - static World* instance() - { - static World instance; - return &instance; - } + static World* instance(); static std::atomic<uint32> m_worldLoopCounter; @@ -882,8 +882,9 @@ class World std::deque<std::future<PreparedQueryResult>> m_realmCharCallbacks; }; -extern uint32 realmID; +TC_GAME_API extern Realm realm; #define sWorld World::instance() + #endif /// @} diff --git a/src/server/scripts/CMakeLists.txt b/src/server/scripts/CMakeLists.txt index a15b6f8ad07..31ba073e77d 100644 --- a/src/server/scripts/CMakeLists.txt +++ b/src/server/scripts/CMakeLists.txt @@ -8,138 +8,232 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# Enable precompiled headers when using the GCC compiler. +message("") -if (USE_SCRIPTPCH) - set(scripts_STAT_PCH_HDR PrecompiledHeaders/ScriptPCH.h) - set(scripts_STAT_PCH_SRC PrecompiledHeaders/ScriptPCH.cpp) -endif () +# Make the script module list available in the current scope +GetScriptModuleList(SCRIPT_MODULE_LIST) + +# Make the native install offset available in this scope +GetInstallOffset(INSTALL_OFFSET) -message(STATUS "SCRIPT PREPARATIONS") -include(Spells/CMakeLists.txt) - -include(Commands/CMakeLists.txt) - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - ../game/AI/ScriptedAI/ScriptedEscortAI.cpp - ../game/AI/ScriptedAI/ScriptedCreature.cpp - ../game/AI/ScriptedAI/ScriptedFollowerAI.cpp - ../game/Maps/AreaBoundary.cpp -) - -if(SCRIPTS) - include(Custom/CMakeLists.txt) - include(World/CMakeLists.txt) - include(OutdoorPvP/CMakeLists.txt) - include(EasternKingdoms/CMakeLists.txt) - include(Kalimdor/CMakeLists.txt) - include(Outland/CMakeLists.txt) - include(Northrend/CMakeLists.txt) - include(Events/CMakeLists.txt) - include(Pet/CMakeLists.txt) +# Sets the SCRIPTS_${SCRIPT_MODULE} variables +# when using predefined templates for script building +# like dynamic, static, minimal-static... +# Sets SCRIPTS_DEFAULT_LINKAGE +if (SCRIPTS MATCHES "dynamic") + set(SCRIPTS_DEFAULT_LINKAGE "dynamic") +elseif(SCRIPTS MATCHES "static") + set(SCRIPTS_DEFAULT_LINKAGE "static") +else() + set(SCRIPTS_DEFAULT_LINKAGE "disabled") +endif() +# Sets SCRIPTS_USE_WHITELIST +# Sets SCRIPTS_WHITELIST +if (SCRIPTS MATCHES "minimal") + set(SCRIPTS_USE_WHITELIST ON) + # Whitelist which is used when minimal is selected + list(APPEND SCRIPTS_WHITELIST Commands Spells) endif() -message(STATUS "SCRIPT PREPARATION COMPLETE") -message("") +# Set the SCRIPTS_${SCRIPT_MODULE} variables from the +# variables set above +foreach(SCRIPT_MODULE ${SCRIPT_MODULE_LIST}) + ScriptModuleNameToVariable(${SCRIPT_MODULE} SCRIPT_MODULE_VARIABLE) + if (${SCRIPT_MODULE_VARIABLE} STREQUAL "default") + if(SCRIPTS_USE_WHITELIST) + list(FIND SCRIPTS_WHITELIST "${SCRIPT_MODULE}" INDEX) + if (${INDEX} GREATER -1) + set(${SCRIPT_MODULE_VARIABLE} ${SCRIPTS_DEFAULT_LINKAGE}) + else() + set(${SCRIPT_MODULE_VARIABLE} "disabled") + endif() + else() + set(${SCRIPT_MODULE_VARIABLE} ${SCRIPTS_DEFAULT_LINKAGE}) + endif() + endif() + # Build the Graph values + if (${SCRIPT_MODULE_VARIABLE} MATCHES "dynamic") + GetProjectNameOfScriptModule(${SCRIPT_MODULE} SCRIPT_MODULE_PROJECT_NAME) + GetNativeSharedLibraryName(${SCRIPT_MODULE_PROJECT_NAME} SCRIPT_PROJECT_LIBRARY) + list(APPEND GRAPH_KEYS ${SCRIPT_MODULE_PROJECT_NAME}) + set(GRAPH_VALUE_DISPLAY_${SCRIPT_MODULE_PROJECT_NAME} ${SCRIPT_PROJECT_LIBRARY}) + list(APPEND GRAPH_VALUE_CONTAINS_MODULES_${SCRIPT_MODULE_PROJECT_NAME} ${SCRIPT_MODULE}) + elseif(${SCRIPT_MODULE_VARIABLE} MATCHES "static") + list(APPEND GRAPH_KEYS worldserver) + set(GRAPH_VALUE_DISPLAY_worldserver worldserver) + list(APPEND GRAPH_VALUE_CONTAINS_MODULES_worldserver ${SCRIPT_MODULE}) + else() + list(APPEND GRAPH_KEYS disabled) + set(GRAPH_VALUE_DISPLAY_disabled disabled) + list(APPEND GRAPH_VALUE_CONTAINS_MODULES_disabled ${SCRIPT_MODULE}) + endif() +endforeach() + +list(SORT GRAPH_KEYS) +list(REMOVE_DUPLICATES GRAPH_KEYS) -include_directories( - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour/Include - ${CMAKE_SOURCE_DIR}/src/common/ - ${CMAKE_SOURCE_DIR}/src/common/Collision - ${CMAKE_SOURCE_DIR}/src/common/Collision/Management - ${CMAKE_SOURCE_DIR}/src/common/Collision/Maps - ${CMAKE_SOURCE_DIR}/src/common/Collision/Models - ${CMAKE_SOURCE_DIR}/src/common/Configuration - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/database/Database - ${CMAKE_SOURCE_DIR}/src/server/game/Accounts - ${CMAKE_SOURCE_DIR}/src/server/game/Achievements - ${CMAKE_SOURCE_DIR}/src/server/game/Addons - ${CMAKE_SOURCE_DIR}/src/server/game/AI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/CoreAI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/ScriptedAI - ${CMAKE_SOURCE_DIR}/src/server/game/AI/SmartScripts - ${CMAKE_SOURCE_DIR}/src/server/game/AuctionHouse - ${CMAKE_SOURCE_DIR}/src/server/game/AuctionHouseBot - ${CMAKE_SOURCE_DIR}/src/server/game/Battlefield - ${CMAKE_SOURCE_DIR}/src/server/game/Battlefield/Zones - ${CMAKE_SOURCE_DIR}/src/server/game/Battlegrounds - ${CMAKE_SOURCE_DIR}/src/server/game/Battlegrounds/Zones - ${CMAKE_SOURCE_DIR}/src/server/game/Chat - ${CMAKE_SOURCE_DIR}/src/server/game/Chat/Channels - ${CMAKE_SOURCE_DIR}/src/server/game/Combat - ${CMAKE_SOURCE_DIR}/src/server/game/Conditions - ${CMAKE_SOURCE_DIR}/src/server/game/DataStores - ${CMAKE_SOURCE_DIR}/src/server/game/DungeonFinding - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Corpse - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Creature - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/DynamicObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/GameObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item/Container - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object/Updates - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Pet - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Player - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Transport - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Unit - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Vehicle - ${CMAKE_SOURCE_DIR}/src/server/game/Events - ${CMAKE_SOURCE_DIR}/src/server/game/Globals - ${CMAKE_SOURCE_DIR}/src/server/game/Grids - ${CMAKE_SOURCE_DIR}/src/server/game/Grids/Cells - ${CMAKE_SOURCE_DIR}/src/server/game/Grids/Notifiers - ${CMAKE_SOURCE_DIR}/src/server/game/Groups - ${CMAKE_SOURCE_DIR}/src/server/game/Guilds - ${CMAKE_SOURCE_DIR}/src/server/game/Handlers - ${CMAKE_SOURCE_DIR}/src/server/game/Instances - ${CMAKE_SOURCE_DIR}/src/server/game/Loot - ${CMAKE_SOURCE_DIR}/src/server/game/Mails - ${CMAKE_SOURCE_DIR}/src/server/game/Maps - ${CMAKE_SOURCE_DIR}/src/server/game/Miscellaneous - ${CMAKE_SOURCE_DIR}/src/server/game/Movement - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/MovementGenerators - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/Spline - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/Waypoints - ${CMAKE_SOURCE_DIR}/src/server/game/OutdoorPvP - ${CMAKE_SOURCE_DIR}/src/server/game/Pools - ${CMAKE_SOURCE_DIR}/src/server/game/Quests - ${CMAKE_SOURCE_DIR}/src/server/game/Reputation - ${CMAKE_SOURCE_DIR}/src/server/game/Scripting - ${CMAKE_SOURCE_DIR}/src/server/game/Server - ${CMAKE_SOURCE_DIR}/src/server/game/Server/Protocol - ${CMAKE_SOURCE_DIR}/src/server/game/Skills - ${CMAKE_SOURCE_DIR}/src/server/game/Spells - ${CMAKE_SOURCE_DIR}/src/server/game/Spells/Auras - ${CMAKE_SOURCE_DIR}/src/server/game/Texts - ${CMAKE_SOURCE_DIR}/src/server/game/Tickets - ${CMAKE_SOURCE_DIR}/src/server/game/Tools - ${CMAKE_SOURCE_DIR}/src/server/game/Warden - ${CMAKE_SOURCE_DIR}/src/server/game/Weather - ${CMAKE_SOURCE_DIR}/src/server/game/World - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/shared/DataStores - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic/LinkedReference - ${CMAKE_SOURCE_DIR}/src/server/shared/Packets - ${MYSQL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) +# Display the script graph +message("* Script configuration (${SCRIPTS}): + |") + +foreach(GRAPH_KEY ${GRAPH_KEYS}) + if (NOT GRAPH_KEY STREQUAL "disabled") + message(" +- ${GRAPH_VALUE_DISPLAY_${GRAPH_KEY}}") + else() + message(" | ${GRAPH_VALUE_DISPLAY_${GRAPH_KEY}}") + endif() + foreach(GRAPH_PROJECT_ENTRY ${GRAPH_VALUE_CONTAINS_MODULES_${GRAPH_KEY}}) + message(" | +- ${GRAPH_PROJECT_ENTRY}") + endforeach() + message(" |") +endforeach() + +# Base sources which are used by every script project +if (USE_SCRIPTPCH) + set(PRIVATE_PCH_HEADER ScriptPCH.h) + set(PRIVATE_PCH_SOURCE ScriptPCH.cpp) +endif () GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) +# Configures the scriptloader with the given name and stores the output in the LOADER_OUT variable. +# It is possible to expose multiple subdirectories from the same scriptloader through passing +# it to the variable arguments +function(ConfigureScriptLoader SCRIPTLOADER_NAME LOADER_OUT IS_DYNAMIC_SCRIPTLOADER) + # Deduces following variables which are referenced by thge template: + # TRINITY_IS_DYNAMIC_SCRIPTLOADER + # TRINITY_SCRIPTS_FORWARD_DECL + # TRINITY_SCRIPTS_INVOKE + # TRINITY_CURRENT_SCRIPT_PROJECT + + # To generate export macros + set(TRINITY_IS_DYNAMIC_SCRIPTLOADER ${IS_DYNAMIC_SCRIPTLOADER}) + # To generate forward declarations of the loading functions + unset(TRINITY_SCRIPTS_FORWARD_DECL) + unset(TRINITY_SCRIPTS_INVOKE) + # The current script project which is built in + set(TRINITY_CURRENT_SCRIPT_PROJECT ${SCRIPTLOADER_NAME}) + foreach(LOCALE_SCRIPT_MODULE ${ARGN}) + # Determine the loader function ("Add##${NameOfDirectory}##Scripts()") + set(LOADER_FUNCTION + "Add${LOCALE_SCRIPT_MODULE}Scripts()") + # Generate the funciton call and the forward declarations + set(TRINITY_SCRIPTS_FORWARD_DECL + "${TRINITY_SCRIPTS_FORWARD_DECL}void ${LOADER_FUNCTION};\n") + set(TRINITY_SCRIPTS_INVOKE + "${TRINITY_SCRIPTS_INVOKE} ${LOADER_FUNCTION};\n") + endforeach() + set(GENERATED_LOADER ${CMAKE_CURRENT_BINARY_DIR}/gen_scriptloader/${SCRIPTLOADER_NAME}/ScriptLoader.cpp) + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/ScriptLoader.cpp.in.cmake ${GENERATED_LOADER}) + set(${LOADER_OUT} ${GENERATED_LOADER} PARENT_SCOPE) +endfunction() + +# Generates the actual script projects +# Fills the STATIC_SCRIPT_MODULES and DYNAMIC_SCRIPT_MODULE_PROJECTS variables +# which contain the names which scripts are linked statically/dynamically and +# adds the sources of the static modules to the PRIVATE_SOURCES variable. +foreach(SCRIPT_MODULE ${SCRIPT_MODULE_LIST}) + GetPathToScriptModule(${SCRIPT_MODULE} SCRIPT_MODULE_PATH) + ScriptModuleNameToVariable(${SCRIPT_MODULE} SCRIPT_MODULE_VARIABLE) + + if ((${SCRIPT_MODULE_VARIABLE} STREQUAL "disabled") OR + (${SCRIPT_MODULE_VARIABLE} STREQUAL "static")) + # Uninstall disabled modules + GetProjectNameOfScriptModule(${SCRIPT_MODULE} SCRIPT_MODULE_PROJECT_NAME) + GetNativeSharedLibraryName(${SCRIPT_MODULE_PROJECT_NAME} SCRIPT_MODULE_OUTPUT_NAME) + list(APPEND DISABLED_SCRIPT_MODULE_PROJECTS ${INSTALL_OFFSET}/${SCRIPT_MODULE_OUTPUT_NAME}) + if (${SCRIPT_MODULE_VARIABLE} STREQUAL "static") + # Add the module name to STATIC_SCRIPT_MODULES + list(APPEND STATIC_SCRIPT_MODULES ${SCRIPT_MODULE}) + # Add the module content to the whole static module + CollectSourceFiles(${SCRIPT_MODULE_PATH} PRIVATE_SOURCES) + endif() + elseif(${SCRIPT_MODULE_VARIABLE} STREQUAL "dynamic") + # Generate an own dynamic module which is loadable on runtime + # Add the module content to the whole static module + unset(SCRIPT_MODULE_PRIVATE_SOURCES) + CollectSourceFiles(${SCRIPT_MODULE_PATH} SCRIPT_MODULE_PRIVATE_SOURCES) + # Configure the scriptloader + ConfigureScriptLoader(${SCRIPT_MODULE} SCRIPT_MODULE_PRIVATE_SCRIPTLOADER ON ${SCRIPT_MODULE}) + GetProjectNameOfScriptModule(${SCRIPT_MODULE} SCRIPT_MODULE_PROJECT_NAME) + # Add the module name to DYNAMIC_SCRIPT_MODULES + list(APPEND DYNAMIC_SCRIPT_MODULE_PROJECTS ${SCRIPT_MODULE_PROJECT_NAME}) + # Create the script module project + add_library(${SCRIPT_MODULE_PROJECT_NAME} SHARED + ${PRIVATE_PCH_SOURCE} + ${SCRIPT_MODULE_PRIVATE_SOURCES} + ${SCRIPT_MODULE_PRIVATE_SCRIPTLOADER}) + target_link_libraries(${SCRIPT_MODULE_PROJECT_NAME} + PUBLIC + game) + set_target_properties(${SCRIPT_MODULE_PROJECT_NAME} + PROPERTIES + FOLDER + "scripts") + + if(UNIX) + install(TARGETS ${SCRIPT_MODULE_PROJECT_NAME} + DESTINATION ${INSTALL_OFFSET} + COMPONENT ${SCRIPT_MODULE_PROJECT_NAME}) + elseif(WIN32) + install(TARGETS ${SCRIPT_MODULE_PROJECT_NAME} + RUNTIME DESTINATION ${INSTALL_OFFSET} + COMPONENT ${SCRIPT_MODULE_PROJECT_NAME}) + if(MSVC) + # Place the script modules in the script subdirectory + set_target_properties(${SCRIPT_MODULE_PROJECT_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/bin/Debug/scripts + RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/bin/Release/scripts + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}/bin/RelWithDebInfo/scripts + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${CMAKE_BINARY_DIR}/bin/MinSizeRel/scripts) + endif() + endif() + else() + message(FATAL_ERROR "Unknown value \"${${SCRIPT_MODULE_VARIABLE}}\"!") + endif() +endforeach() + +# Add the dynamic script modules to the worldserver as dependency +set(WORLDSERVER_DYNAMIC_SCRIPT_MODULES_DEPENDENCIES ${DYNAMIC_SCRIPT_MODULE_PROJECTS} PARENT_SCOPE) + +ConfigureScriptLoader("static" SCRIPT_MODULE_PRIVATE_SCRIPTLOADER OFF ${STATIC_SCRIPT_MODULES}) + add_library(scripts STATIC - ${scripts_STAT_SRCS} - ${scripts_STAT_PCH_SRC} -) + ScriptLoader.h + ${PRIVATE_PCH_SOURCE} + ${SCRIPT_MODULE_PRIVATE_SCRIPTLOADER} + ${PRIVATE_SOURCES}) + +target_link_libraries(scripts + PUBLIC + game-interface) + +target_include_directories(scripts + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}) + +set_target_properties(scripts + PROPERTIES + FOLDER + "scripts") # Generate precompiled header if (USE_SCRIPTPCH) - add_cxx_pch(scripts ${scripts_STAT_PCH_HDR} ${scripts_STAT_PCH_SRC}) + list(APPEND ALL_SCRIPT_PROJECTS scripts ${DYNAMIC_SCRIPT_MODULE_PROJECTS}) + add_cxx_pch("${ALL_SCRIPT_PROJECTS}" ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) +endif() + +# Remove all shared libraries in the installl directory which +# are contained in the static library already. +if (DISABLED_SCRIPT_MODULE_PROJECTS) + install(CODE " + foreach(SCRIPT_TO_UNINSTALL ${DISABLED_SCRIPT_MODULE_PROJECTS}) + if (EXISTS \"\${SCRIPT_TO_UNINSTALL}\") + message(STATUS \"Uninstalling: \${SCRIPT_TO_UNINSTALL}\") + file(REMOVE \"\${SCRIPT_TO_UNINSTALL}\") + endif() + endforeach() + ") endif() + +message("") diff --git a/src/server/scripts/Commands/CMakeLists.txt b/src/server/scripts/Commands/CMakeLists.txt deleted file mode 100644 index d4d75cd175f..00000000000 --- a/src/server/scripts/Commands/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB_RECURSE sources_Commands Commands/*.cpp Commands/*.h) - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - ${sources_Commands} -) - -message(" -> Prepared: Commands") diff --git a/src/server/scripts/Commands/cs_account.cpp b/src/server/scripts/Commands/cs_account.cpp index f25e91ee3e6..4bce2d168a9 100644 --- a/src/server/scripts/Commands/cs_account.cpp +++ b/src/server/scripts/Commands/cs_account.cpp @@ -121,10 +121,16 @@ public: if (!accountName || !password) return false; - AccountOpResult result = sAccountMgr->CreateAccount(std::string(accountName), std::string(password), email); - switch (result) + if (strchr(accountName, '@')) + { + handler->PSendSysMessage(LANG_ACCOUNT_USE_BNET_COMMANDS); + handler->SetSentErrorMessage(true); + return false; + } + + switch (sAccountMgr->CreateAccount(std::string(accountName), std::string(password), email)) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->PSendSysMessage(LANG_ACCOUNT_CREATED, accountName); if (handler->GetSession()) { @@ -134,15 +140,15 @@ public: accountName, email.c_str()); } break; - case AOR_NAME_TOO_LONG: + case AccountOpResult::AOR_NAME_TOO_LONG: handler->SendSysMessage(LANG_ACCOUNT_TOO_LONG); handler->SetSentErrorMessage(true); return false; - case AOR_NAME_ALREADY_EXIST: + case AccountOpResult::AOR_NAME_ALREADY_EXIST: handler->SendSysMessage(LANG_ACCOUNT_ALREADY_EXIST); handler->SetSentErrorMessage(true); return false; - case AOR_DB_INTERNAL_ERROR: + case AccountOpResult::AOR_DB_INTERNAL_ERROR: handler->PSendSysMessage(LANG_ACCOUNT_NOT_CREATED_SQL_ERROR, accountName); handler->SetSentErrorMessage(true); return false; @@ -168,7 +174,7 @@ public: return false; std::string accountName = account; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -192,14 +198,14 @@ public: AccountOpResult result = AccountMgr::DeleteAccount(accountId); switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->PSendSysMessage(LANG_ACCOUNT_DELETED, accountName.c_str()); break; - case AOR_NAME_NOT_EXIST: + case AccountOpResult::AOR_NAME_NOT_EXIST: handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); return false; - case AOR_DB_INTERNAL_ERROR: + case AccountOpResult::AOR_DB_INTERNAL_ERROR: handler->PSendSysMessage(LANG_ACCOUNT_NOT_DELETED_SQL_ERROR, accountName.c_str()); handler->SetSentErrorMessage(true); return false; @@ -415,7 +421,7 @@ public: AccountOpResult result = AccountMgr::ChangeEmail(handler->GetSession()->GetAccountId(), std::string(email)); switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->SendSysMessage(LANG_COMMAND_EMAIL); sScriptMgr->OnEmailChange(handler->GetSession()->GetAccountId()); TC_LOG_INFO("entities.player.character", "Account: %u (IP: %s) Character:[%s] (GUID: %u) Changed Email from [%s] to [%s].", @@ -423,7 +429,7 @@ public: handler->GetSession()->GetPlayer()->GetName().c_str(), handler->GetSession()->GetPlayer()->GetGUID().GetCounter(), oldEmail, email); break; - case AOR_EMAIL_TOO_LONG: + case AccountOpResult::AOR_EMAIL_TOO_LONG: handler->SendSysMessage(LANG_EMAIL_TOO_LONG); sScriptMgr->OnFailedEmailChange(handler->GetSession()->GetAccountId()); handler->SetSentErrorMessage(true); @@ -505,14 +511,14 @@ public: AccountOpResult result = AccountMgr::ChangePassword(handler->GetSession()->GetAccountId(), std::string(newPassword)); switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->SendSysMessage(LANG_COMMAND_PASSWORD); sScriptMgr->OnPasswordChange(handler->GetSession()->GetAccountId()); TC_LOG_INFO("entities.player.character", "Account: %u (IP: %s) Character:[%s] (GUID: %u) Changed Password.", handler->GetSession()->GetAccountId(), handler->GetSession()->GetRemoteAddress().c_str(), handler->GetSession()->GetPlayer()->GetName().c_str(), handler->GetSession()->GetPlayer()->GetGUID().GetCounter()); break; - case AOR_PASS_TOO_LONG: + case AccountOpResult::AOR_PASS_TOO_LONG: handler->SendSysMessage(LANG_PASSWORD_TOO_LONG); sScriptMgr->OnFailedPasswordChange(handler->GetSession()->GetAccountId()); handler->SetSentErrorMessage(true); @@ -592,7 +598,7 @@ public: { ///- Convert Account name to Upper Format accountName = account; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -662,7 +668,7 @@ public: if (isAccountNameGiven) { targetAccountName = arg1; - if (!AccountMgr::normalizeString(targetAccountName) || !AccountMgr::GetId(targetAccountName)) + if (!Utf8ToUpperOnlyLatin(targetAccountName) || !AccountMgr::GetId(targetAccountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, targetAccountName.c_str()); handler->SetSentErrorMessage(true); @@ -750,7 +756,7 @@ public: return false; std::string accountName = account; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -781,14 +787,14 @@ public: switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->SendSysMessage(LANG_COMMAND_PASSWORD); break; - case AOR_NAME_NOT_EXIST: + case AccountOpResult::AOR_NAME_NOT_EXIST: handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); return false; - case AOR_PASS_TOO_LONG: + case AccountOpResult::AOR_PASS_TOO_LONG: handler->SendSysMessage(LANG_PASSWORD_TOO_LONG); handler->SetSentErrorMessage(true); return false; @@ -819,7 +825,7 @@ public: } std::string accountName = account; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -849,16 +855,16 @@ public: AccountOpResult result = AccountMgr::ChangeEmail(targetAccountId, email); switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->SendSysMessage(LANG_COMMAND_EMAIL); TC_LOG_INFO("entities.player.character", "ChangeEmail: Account %s [Id: %u] had it's email changed to %s.", accountName.c_str(), targetAccountId, email); break; - case AOR_NAME_NOT_EXIST: + case AccountOpResult::AOR_NAME_NOT_EXIST: handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); return false; - case AOR_EMAIL_TOO_LONG: + case AccountOpResult::AOR_EMAIL_TOO_LONG: handler->SendSysMessage(LANG_EMAIL_TOO_LONG); handler->SetSentErrorMessage(true); return false; @@ -895,7 +901,7 @@ public: } std::string accountName = account; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -925,16 +931,16 @@ public: AccountOpResult result = AccountMgr::ChangeRegEmail(targetAccountId, email); switch (result) { - case AOR_OK: + case AccountOpResult::AOR_OK: handler->SendSysMessage(LANG_COMMAND_EMAIL); TC_LOG_INFO("entities.player.character", "ChangeRegEmail: Account %s [Id: %u] had it's Registration Email changed to %s.", accountName.c_str(), targetAccountId, email); break; - case AOR_NAME_NOT_EXIST: + case AccountOpResult::AOR_NAME_NOT_EXIST: handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); return false; - case AOR_EMAIL_TOO_LONG: + case AccountOpResult::AOR_EMAIL_TOO_LONG: handler->SendSysMessage(LANG_EMAIL_TOO_LONG); handler->SetSentErrorMessage(true); return false; diff --git a/src/server/scripts/Commands/cs_ahbot.cpp b/src/server/scripts/Commands/cs_ahbot.cpp index 65e90394261..47553d085b1 100644 --- a/src/server/scripts/Commands/cs_ahbot.cpp +++ b/src/server/scripts/Commands/cs_ahbot.cpp @@ -33,7 +33,7 @@ class ahbot_commandscript : public CommandScript public: ahbot_commandscript(): CommandScript("ahbot_commandscript") {} - std::vector<ChatCommand> GetCommands() const + std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> ahbotItemsAmountCommandTable = { diff --git a/src/server/scripts/Commands/cs_ban.cpp b/src/server/scripts/Commands/cs_ban.cpp index 4a1bf71e1d8..ba512dbf8eb 100644 --- a/src/server/scripts/Commands/cs_ban.cpp +++ b/src/server/scripts/Commands/cs_ban.cpp @@ -171,7 +171,7 @@ public: switch (mode) { case BAN_ACCOUNT: - if (!AccountMgr::normalizeString(nameOrIP)) + if (!Utf8ToUpperOnlyLatin(nameOrIP)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); handler->SetSentErrorMessage(true); @@ -244,7 +244,7 @@ public: return false; std::string accountName = nameStr; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -712,7 +712,7 @@ public: switch (mode) { case BAN_ACCOUNT: - if (!AccountMgr::normalizeString(nameOrIP)) + if (!Utf8ToUpperOnlyLatin(nameOrIP)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); handler->SetSentErrorMessage(true); diff --git a/src/server/scripts/Commands/cs_character.cpp b/src/server/scripts/Commands/cs_character.cpp index e048aabd4d7..01602e2f24c 100644 --- a/src/server/scripts/Commands/cs_character.cpp +++ b/src/server/scripts/Commands/cs_character.cpp @@ -133,7 +133,7 @@ public: info.name = fields[1].GetString(); info.accountId = fields[2].GetUInt32(); - // account name will be empty for not existed account + // account name will be empty for nonexisting account AccountMgr::GetName(info.accountId, info.accountName); info.deleteDate = time_t(fields[3].GetUInt32()); foundList.push_back(info); @@ -169,11 +169,11 @@ public: if (!handler->GetSession()) handler->PSendSysMessage(LANG_CHARACTER_DELETED_LIST_LINE_CONSOLE, - itr->guid.GetCounter(), itr->name.c_str(), itr->accountName.empty() ? "<Not existed>" : itr->accountName.c_str(), + itr->guid.GetCounter(), itr->name.c_str(), itr->accountName.empty() ? "<Not existing>" : itr->accountName.c_str(), itr->accountId, dateStr.c_str()); else handler->PSendSysMessage(LANG_CHARACTER_DELETED_LIST_LINE_CHAT, - itr->guid.GetCounter(), itr->name.c_str(), itr->accountName.empty() ? "<Not existed>" : itr->accountName.c_str(), + itr->guid.GetCounter(), itr->name.c_str(), itr->accountName.empty() ? "<Not existing>" : itr->accountName.c_str(), itr->accountId, dateStr.c_str()); } @@ -193,7 +193,7 @@ public: */ static void HandleCharacterDeletedRestoreHelper(DeletedInfo const& delInfo, ChatHandler* handler) { - if (delInfo.accountName.empty()) // account not exist + if (delInfo.accountName.empty()) // account does not exist { handler->PSendSysMessage(LANG_CHARACTER_DELETED_SKIP_ACCOUNT, delInfo.name.c_str(), delInfo.guid.GetCounter(), delInfo.accountId); return; @@ -436,7 +436,7 @@ public: if (isalpha(levelStr[0])) { nameStr = levelStr; - levelStr = NULL; // current level will used + levelStr = nullptr; // current level will used } Player* target; @@ -660,7 +660,7 @@ public: if (newCharName.empty()) { - // Drop not existed account cases + // Drop nonexisting account cases for (DeletedInfoList::iterator itr = foundList.begin(); itr != foundList.end(); ++itr) HandleCharacterDeletedRestoreHelper(*itr, handler); } @@ -810,7 +810,7 @@ public: if (levelStr && isalpha(levelStr[0])) { nameStr = levelStr; - levelStr = NULL; // current level will used + levelStr = NULL; // current level will be used } Player* target; @@ -854,7 +854,7 @@ public: return false; std::string accountName = accountStr; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); diff --git a/src/server/scripts/Commands/cs_debug.cpp b/src/server/scripts/Commands/cs_debug.cpp index b937fc4e0a4..570f4587ae8 100644 --- a/src/server/scripts/Commands/cs_debug.cpp +++ b/src/server/scripts/Commands/cs_debug.cpp @@ -34,8 +34,11 @@ EndScriptData */ #include "Transport.h" #include "Language.h" #include "MapManager.h" +#include "M2Stores.h" +#include "BattlefieldMgr.h" #include <fstream> +#include <limits> class debug_commandscript : public CommandScript { @@ -94,7 +97,8 @@ public: { "transport", rbac::RBAC_PERM_COMMAND_DEBUG_TRANSPORT, false, &HandleDebugTransportCommand, "" }, { "loadcells", rbac::RBAC_PERM_COMMAND_DEBUG_LOADCELLS, false, &HandleDebugLoadCellsCommand, "" }, { "boundary", rbac::RBAC_PERM_COMMAND_DEBUG_BOUNDARY, false, &HandleDebugBoundaryCommand, "" }, - { "raidreset", rbac::RBAC_PERM_COMMAND_INSTANCE_UNBIND, false, &HandleDebugRaidResetCommand, "" } + { "raidreset", rbac::RBAC_PERM_COMMAND_INSTANCE_UNBIND, false, &HandleDebugRaidResetCommand, "" }, + { "neargraveyard", rbac::RBAC_PERM_COMMAND_NEARGRAVEYARD, false, &HandleDebugNearGraveyard, "" }, }; static std::vector<ChatCommand> commandTable = { @@ -124,6 +128,23 @@ public: return false; } + // Dump camera locations + if (CinematicSequencesEntry const* cineSeq = sCinematicSequencesStore.LookupEntry(id)) + { + std::unordered_map<uint32, FlyByCameraCollection>::const_iterator itr = sFlyByCameraStore.find(cineSeq->cinematicCamera); + if (itr != sFlyByCameraStore.end()) + { + handler->PSendSysMessage("Waypoints for sequence %u, camera %u", id, cineSeq->cinematicCamera); + uint32 count = 1 ; + for (FlyByCamera cam : itr->second) + { + handler->PSendSysMessage("%02u - %7ums [%f, %f, %f] Facing %f (%f degrees)", count, cam.timeStamp, cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w, cam.locations.w * (180 / M_PI)); + count++; + } + handler->PSendSysMessage("%u waypoints dumped", itr->second.size()); + } + } + handler->GetSession()->GetPlayer()->SendCinematicStart(id); return true; } @@ -830,7 +851,7 @@ public: if (Unit* unit = ref->GetSource()->GetOwner()) { ++count; - handler->PSendSysMessage(" %u. %s (guid %u) - threat %f", count, unit->GetName().c_str(), unit->GetGUID().GetCounter(), ref->getThreat()); + handler->PSendSysMessage(" %u. %s (current guid %u, DB guid %u) - threat %f", count, unit->GetName().c_str(), unit->GetGUID().GetCounter(), unit->GetTypeId() == TYPEID_UNIT ? unit->ToCreature()->GetSpawnId() : 0, ref->getThreat()); } ref = ref->next(); } @@ -1045,7 +1066,8 @@ public: return false; uint32 animId = atoi((char*)args); - handler->GetSession()->GetPlayer()->HandleEmoteCommand(animId); + if (Unit* unit = handler->getSelectedUnit()) + unit->HandleEmoteCommand(animId); return true; } @@ -1409,10 +1431,7 @@ public: map = player->GetMap(); handler->PSendSysMessage("Loading all cells (mapId: %u). Current next GameObject %u, Creature %u", map->GetId(), map->GetMaxLowGuid<HighGuid::GameObject>(), map->GetMaxLowGuid<HighGuid::Unit>()); - for (uint32 cellX = 0; cellX < TOTAL_NUMBER_OF_CELLS_PER_MAP; cellX++) - for (uint32 cellY = 0; cellY < TOTAL_NUMBER_OF_CELLS_PER_MAP; cellY++) - map->LoadGrid((cellX + 0.5f - CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL, (cellY + 0.5f - CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL); - + map->LoadAllCells(); handler->PSendSysMessage("Cells loaded (mapId: %u) After load - Next GameObject %u, Creature %u", map->GetId(), map->GetMaxLowGuid<HighGuid::GameObject>(), map->GetMaxLowGuid<HighGuid::Unit>()); return true; } @@ -1436,7 +1455,7 @@ public: duration = 3 * MINUTE; bool doFill = fill_str ? (stricmp(fill_str, "FILL") == 0) : false; - + int32 errMsg = target->AI()->VisualizeBoundary(duration, player, doFill); if (errMsg > 0) handler->PSendSysMessage(errMsg); @@ -1469,6 +1488,53 @@ public: sInstanceSaveMgr->ForceGlobalReset(mEntry->MapID, Difficulty(difficulty)); return true; } + + static bool HandleDebugNearGraveyard(ChatHandler* handler, char const* args) + { + Player* player = handler->GetSession()->GetPlayer(); + const WorldSafeLocsEntry* nearestLoc = nullptr; + + if (stricmp(args, "linked")) + { + if (Battleground* bg = player->GetBattleground()) + nearestLoc = bg->GetClosestGraveYard(player); + else + { + if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) + nearestLoc = bf->GetClosestGraveYard(player); + else + nearestLoc = sObjectMgr->GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), player->GetTeam()); + } + } + else + { + float x = player->GetPositionX(); + float y = player->GetPositionY(); + float z = player->GetPositionZ(); + float distNearest = std::numeric_limits<float>::max(); + + for (uint32 i = 0; i < sWorldSafeLocsStore.GetNumRows(); ++i) + { + const WorldSafeLocsEntry* loc = sWorldSafeLocsStore.LookupEntry(i); + if (loc && loc->map_id == player->GetMapId()) + { + float dist = (loc->x - x) * (loc->x - x) + (loc->y - y) * (loc->y - y) + (loc->z - z) * (loc->z - z); + if (dist < distNearest) + { + distNearest = dist; + nearestLoc = loc; + } + } + } + } + + if (nearestLoc) + handler->PSendSysMessage(LANG_COMMAND_NEARGRAVEYARD, nearestLoc->ID, nearestLoc->x, nearestLoc->y, nearestLoc->z); + else + handler->PSendSysMessage(LANG_COMMAND_NEARGRAVEYARD_NOTFOUND); + + return true; + } }; void AddSC_debug_commandscript() diff --git a/src/server/scripts/Commands/cs_gm.cpp b/src/server/scripts/Commands/cs_gm.cpp index e03942bc247..ffe8ea67816 100644 --- a/src/server/scripts/Commands/cs_gm.cpp +++ b/src/server/scripts/Commands/cs_gm.cpp @@ -164,7 +164,7 @@ public: ///- Get the accounts with GM Level >0 PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_GM_ACCOUNTS); stmt->setUInt8(0, uint8(SEC_MODERATOR)); - stmt->setInt32(1, int32(realmID)); + stmt->setInt32(1, int32(realm.Id.Realm)); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) diff --git a/src/server/scripts/Commands/cs_gobject.cpp b/src/server/scripts/Commands/cs_gobject.cpp index 729dac0ad6f..c4ed6f650b9 100644 --- a/src/server/scripts/Commands/cs_gobject.cpp +++ b/src/server/scripts/Commands/cs_gobject.cpp @@ -139,16 +139,12 @@ public: } Player* player = handler->GetSession()->GetPlayer(); - float x = float(player->GetPositionX()); - float y = float(player->GetPositionY()); - float z = float(player->GetPositionZ()); - float o = float(player->GetOrientation()); Map* map = player->GetMap(); GameObject* object = new GameObject; ObjectGuid::LowType guidLow = map->GenerateLowGuid<HighGuid::GameObject>(); - if (!object->Create(guidLow, objectInfo->entry, map, player->GetPhaseMaskForSpawn(), x, y, z, o, 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY)) + if (!object->Create(guidLow, objectInfo->entry, map, player->GetPhaseMaskForSpawn(), *player, G3D::Quat(), 255, GO_STATE_READY)) { delete object; return false; @@ -179,7 +175,7 @@ public: /// @todo is it really necessary to add both the real and DB table guid here ? sObjectMgr->AddGameobjectToGrid(guidLow, sObjectMgr->GetGOData(guidLow)); - handler->PSendSysMessage(LANG_GAMEOBJECT_ADD, objectId, objectInfo->name.c_str(), guidLow, x, y, z); + handler->PSendSysMessage(LANG_GAMEOBJECT_ADD, objectId, objectInfo->name.c_str(), guidLow, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); return true; } @@ -201,14 +197,7 @@ public: if (spawntime) spawntm = atoi((char*)spawntime); - float x = player->GetPositionX(); - float y = player->GetPositionY(); - float z = player->GetPositionZ(); - float ang = player->GetOrientation(); - - float rot2 = std::sin(ang/2); - float rot3 = std::cos(ang/2); - + G3D::Quat rotation = G3D::Matrix3::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); uint32 objectId = atoi(id); if (!sObjectMgr->GetGameObjectTemplate(objectId)) @@ -218,7 +207,7 @@ public: return false; } - player->SummonGameObject(objectId, x, y, z, ang, 0, 0, rot2, rot3, spawntm); + player->SummonGameObject(objectId, *player, rotation, spawntm); return true; } @@ -415,20 +404,30 @@ public: } char* orientation = strtok(NULL, " "); - float o; + float oz = 0.f, oy = 0.f, ox = 0.f; if (orientation) - o = (float)atof(orientation); + { + oz = float(atof(orientation)); + + orientation = strtok(NULL, " "); + if (orientation) + { + oy = float(atof(orientation)); + orientation = strtok(NULL, " "); + if (orientation) + ox = float(atof(orientation)); + } + } else { Player* player = handler->GetSession()->GetPlayer(); - o = player->GetOrientation(); + oz = player->GetOrientation(); } Map* map = object->GetMap(); - - object->Relocate(object->GetPositionX(), object->GetPositionY(), object->GetPositionZ(), o); - object->UpdateRotationFields(); + object->Relocate(object->GetPositionX(), object->GetPositionY(), object->GetPositionZ()); + object->SetWorldRotationAngles(oz, oy, ox); object->SaveToDB(); // Generate a completely new spawn with new guid diff --git a/src/server/scripts/Commands/cs_lookup.cpp b/src/server/scripts/Commands/cs_lookup.cpp index 61e6acfb4d8..161ade1a30f 100644 --- a/src/server/scripts/Commands/cs_lookup.cpp +++ b/src/server/scripts/Commands/cs_lookup.cpp @@ -1343,7 +1343,7 @@ public: char* limitStr = strtok(NULL, " "); int32 limit = limitStr ? atoi(limitStr) : -1; - if (!AccountMgr::normalizeString + if (!Utf8ToUpperOnlyLatin (account)) return false; diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index c70246f7fb5..16217fbaea6 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -36,6 +36,7 @@ #include "MMapFactory.h" #include "DisableMgr.h" #include "SpellHistory.h" +#include "Transport.h" class misc_commandscript : public CommandScript { @@ -237,6 +238,10 @@ public: areaId, (areaEntry ? areaEntry->area_name[handler->GetSessionDbcLocale()] : unknown), object->GetPhaseMask(), object->GetPositionX(), object->GetPositionY(), object->GetPositionZ(), object->GetOrientation()); + if (Transport* transport = object->GetTransport()) + handler->PSendSysMessage(LANG_TRANSPORT_POSITION, + transport->GetGOInfo()->moTransport.mapID, object->GetTransOffsetX(), object->GetTransOffsetY(), object->GetTransOffsetZ(), object->GetTransOffsetO(), + transport->GetEntry(), transport->GetName().c_str()); handler->PSendSysMessage(LANG_GRID_POSITION, cell.GridX(), cell.GridY(), cell.CellX(), cell.CellY(), object->GetInstanceId(), zoneX, zoneY, groundZ, floorZ, haveMap, haveVMap, haveMMap); @@ -698,7 +703,7 @@ public: static bool HandleCooldownCommand(ChatHandler* handler, char const* args) { - Player* target = handler->getSelectedPlayerOrSelf(); + Unit* target = handler->getSelectedUnit(); if (!target) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); @@ -706,7 +711,14 @@ public: return false; } - std::string nameLink = handler->GetNameLink(target); + Player* owner = target->GetCharmerOrOwnerPlayerOrPlayerItself(); + if (!owner) + { + owner = handler->GetSession()->GetPlayer(); + target = owner; + } + + std::string nameLink = handler->GetNameLink(owner); if (!*args) { @@ -723,13 +735,13 @@ public: SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellIid); if (!spellInfo) { - handler->PSendSysMessage(LANG_UNKNOWN_SPELL, target == handler->GetSession()->GetPlayer() ? handler->GetTrinityString(LANG_YOU) : nameLink.c_str()); + handler->PSendSysMessage(LANG_UNKNOWN_SPELL, owner == handler->GetSession()->GetPlayer() ? handler->GetTrinityString(LANG_YOU) : nameLink.c_str()); handler->SetSentErrorMessage(true); return false; } target->GetSpellHistory()->ResetCooldown(spellIid, true); - handler->PSendSysMessage(LANG_REMOVE_COOLDOWN, spellIid, target == handler->GetSession()->GetPlayer() ? handler->GetTrinityString(LANG_YOU) : nameLink.c_str()); + handler->PSendSysMessage(LANG_REMOVE_COOLDOWN, spellIid, owner == handler->GetSession()->GetPlayer() ? handler->GetTrinityString(LANG_YOU) : nameLink.c_str()); } return true; } @@ -791,7 +803,7 @@ public: target->CleanupAfterTaxiFlight(); } - target->TeleportTo(target->m_recallMap, target->m_recallX, target->m_recallY, target->m_recallZ, target->m_recallO); + target->Recall(); return true; } @@ -1588,7 +1600,7 @@ public: // Query the prepared statement for login data stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PINFO); - stmt->setInt32(0, int32(realmID)); + stmt->setInt32(0, int32(realm.Id.Realm)); stmt->setUInt32(1, accId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -1964,7 +1976,7 @@ public: return false; std::string accountName = nameStr; - if (!AccountMgr::normalizeString(accountName)) + if (!Utf8ToUpperOnlyLatin(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); @@ -2119,17 +2131,9 @@ public: } return true; } - /* - ComeToMe command REQUIRED for 3rd party scripting library to have access to PointMovementGenerator - Without this function 3rd party scripting library will get linking errors (unresolved external) - when attempting to use the PointMovementGenerator - */ - static bool HandleComeToMeCommand(ChatHandler* handler, char const* args) - { - char const* newFlagStr = strtok((char*)args, " "); - if (!newFlagStr) - return false; + static bool HandleComeToMeCommand(ChatHandler* handler, char const* /*args*/) + { Creature* caster = handler->getSelectedCreature(); if (!caster) { diff --git a/src/server/scripts/Commands/cs_modify.cpp b/src/server/scripts/Commands/cs_modify.cpp index 761b4c9e0e6..e25018cf1bd 100644 --- a/src/server/scripts/Commands/cs_modify.cpp +++ b/src/server/scripts/Commands/cs_modify.cpp @@ -80,23 +80,32 @@ public: return commandTable; } - //Edit Player HP - static bool HandleModifyHPCommand(ChatHandler* handler, const char* args) + template<typename... Args> + static void NotifyModification(ChatHandler* handler, Unit* target, TrinityStrings resourceMessage, TrinityStrings resourceReportMessage, Args&&... args) + { + if (Player* player = target->ToPlayer()) + { + handler->PSendSysMessage(resourceMessage, handler->GetNameLink(player).c_str(), args...); + if (handler->needReportToTarget(player)) + ChatHandler(player->GetSession()).PSendSysMessage(resourceReportMessage, handler->GetNameLink().c_str(), std::forward<Args>(args)...); + } + } + + static bool CheckModifyResources(ChatHandler* handler, const char* args, Player* target, int32& res, int32& resmax, int8 const multiplier = 1) { if (!*args) return false; - int32 hp = atoi((char*)args); - int32 hpm = atoi((char*)args); + res = atoi((char*)args) * multiplier; + resmax = atoi((char*)args) * multiplier; - if (hp < 1 || hpm < 1 || hpm < hp) + if (res < 1 || resmax < 1 || resmax < res) { handler->SendSysMessage(LANG_BAD_VALUE); handler->SetSentErrorMessage(true); return false; } - Player* target = handler->getSelectedPlayerOrSelf(); if (!target) { handler->SendSysMessage(LANG_NO_CHAR_SELECTED); @@ -107,164 +116,87 @@ public: if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) return false; - handler->PSendSysMessage(LANG_YOU_CHANGE_HP, handler->GetNameLink(target).c_str(), hp, hpm); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_HP_CHANGED, handler->GetNameLink().c_str(), hp, hpm); - - target->SetMaxHealth(hpm); - target->SetHealth(hp); - return true; } - //Edit Player Mana - static bool HandleModifyManaCommand(ChatHandler* handler, const char* args) + //Edit Player HP + static bool HandleModifyHPCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - int32 mana = atoi((char*)args); - int32 manam = atoi((char*)args); - - if (mana <= 0 || manam <= 0 || manam < mana) + int32 hp, hpmax; + Player* target = handler->getSelectedPlayerOrSelf(); + if (CheckModifyResources(handler, args, target, hp, hpmax)) { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_HP, LANG_YOURS_HP_CHANGED, hp, hpmax); + target->SetMaxHealth(hpmax); + target->SetHealth(hp); + return true; } + return false; + } + //Edit Player Mana + static bool HandleModifyManaCommand(ChatHandler* handler, const char* args) + { + int32 mana, manamax; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + + if (CheckModifyResources(handler, args, target, mana, manamax)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_MANA, LANG_YOURS_MANA_CHANGED, mana, manamax); + target->SetMaxPower(POWER_MANA, manamax); + target->SetPower(POWER_MANA, mana); + return true; } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - handler->PSendSysMessage(LANG_YOU_CHANGE_MANA, handler->GetNameLink(target).c_str(), mana, manam); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_MANA_CHANGED, handler->GetNameLink().c_str(), mana, manam); - - target->SetMaxPower(POWER_MANA, manam); - target->SetPower(POWER_MANA, mana); - - return true; + return false; } //Edit Player Energy static bool HandleModifyEnergyCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - int32 energy = atoi((char*)args)*10; - int32 energym = atoi((char*)args)*10; - - if (energy <= 0 || energym <= 0 || energym < energy) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + int32 energy, energymax; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + int8 const energyMultiplier = 10; + if (CheckModifyResources(handler, args, target, energy, energymax, energyMultiplier)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_ENERGY, LANG_YOURS_ENERGY_CHANGED, energy / energyMultiplier, energymax / energyMultiplier); + target->SetMaxPower(POWER_ENERGY, energymax); + target->SetPower(POWER_ENERGY, energy); + TC_LOG_DEBUG("misc", handler->GetTrinityString(LANG_CURRENT_ENERGY), target->GetMaxPower(POWER_ENERGY)); + return true; } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - handler->PSendSysMessage(LANG_YOU_CHANGE_ENERGY, handler->GetNameLink(target).c_str(), energy/10, energym/10); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_ENERGY_CHANGED, handler->GetNameLink().c_str(), energy/10, energym/10); - - target->SetMaxPower(POWER_ENERGY, energym); - target->SetPower(POWER_ENERGY, energy); - - TC_LOG_DEBUG("misc", handler->GetTrinityString(LANG_CURRENT_ENERGY), target->GetMaxPower(POWER_ENERGY)); - - return true; + return false; } //Edit Player Rage static bool HandleModifyRageCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - int32 rage = atoi((char*)args)*10; - int32 ragem = atoi((char*)args)*10; - - if (rage <= 0 || ragem <= 0 || ragem < rage) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + int32 rage, ragemax; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + int8 const rageMultiplier = 10; + if (CheckModifyResources(handler, args, target, rage, ragemax, rageMultiplier)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_RAGE, LANG_YOURS_RAGE_CHANGED, rage / rageMultiplier, ragemax / rageMultiplier); + target->SetMaxPower(POWER_RAGE, ragemax); + target->SetPower(POWER_RAGE, rage); + return true; } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - handler->PSendSysMessage(LANG_YOU_CHANGE_RAGE, handler->GetNameLink(target).c_str(), rage/10, ragem/10); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_RAGE_CHANGED, handler->GetNameLink().c_str(), rage/10, ragem/10); - - target->SetMaxPower(POWER_RAGE, ragem); - target->SetPower(POWER_RAGE, rage); - - return true; + return false; } // Edit Player Runic Power static bool HandleModifyRunicPowerCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - int32 rune = atoi((char*)args)*10; - int32 runem = atoi((char*)args)*10; - - if (rune <= 0 || runem <= 0 || runem < rune) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + int32 rune, runemax; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + int8 const runeMultiplier = 10; + if (CheckModifyResources(handler, args, target, rune, runemax, runeMultiplier)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_RUNIC_POWER, LANG_YOURS_RUNIC_POWER_CHANGED, rune / runeMultiplier, runemax / runeMultiplier); + target->SetMaxPower(POWER_RUNIC_POWER, runemax); + target->SetPower(POWER_RUNIC_POWER, rune); + return true; } - - handler->PSendSysMessage(LANG_YOU_CHANGE_RUNIC_POWER, handler->GetNameLink(target).c_str(), rune/10, runem/10); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_RUNIC_POWER_CHANGED, handler->GetNameLink().c_str(), rune/10, runem/10); - - target->SetMaxPower(POWER_RUNIC_POWER, runem); - target->SetPower(POWER_RUNIC_POWER, rune); - - return true; + return false; } //Edit Player Faction @@ -437,22 +369,20 @@ public: return false; } - //Edit Player Aspeed - static bool HandleModifyASpeedCommand(ChatHandler* handler, const char* args) + static bool CheckModifySpeed(ChatHandler* handler, const char* args, Unit* target, float& speed, float minimumBound, float maximumBound, bool checkInFlight = true) { if (!*args) return false; - float ASpeed = (float)atof((char*)args); + speed = (float)atof((char*)args); - if (ASpeed > 50.0f || ASpeed < 0.1f) + if (speed > maximumBound || speed < minimumBound) { handler->SendSysMessage(LANG_BAD_VALUE); handler->SetSentErrorMessage(true); return false; } - Player* target = handler->getSelectedPlayerOrSelf(); if (!target) { handler->SendSysMessage(LANG_NO_CHAR_SELECTED); @@ -460,238 +390,107 @@ public: return false; } - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - std::string targetNameLink = handler->GetNameLink(target); - - if (target->IsInFlight()) + if (Player* player = target->ToPlayer()) { - handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str()); - handler->SetSentErrorMessage(true); - return false; - } - - handler->PSendSysMessage(LANG_YOU_CHANGE_ASPEED, ASpeed, targetNameLink.c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_ASPEED_CHANGED, handler->GetNameLink().c_str(), ASpeed); + // check online security + if (handler->HasLowerSecurity(player, ObjectGuid::Empty)) + return false; - target->SetSpeed(MOVE_WALK, ASpeed, true); - target->SetSpeed(MOVE_RUN, ASpeed, true); - target->SetSpeed(MOVE_SWIM, ASpeed, true); - //target->SetSpeed(MOVE_TURN, ASpeed, true); - target->SetSpeed(MOVE_FLIGHT, ASpeed, true); + if (player->IsInFlight() && checkInFlight) + { + handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, handler->GetNameLink(player).c_str()); + handler->SetSentErrorMessage(true); + return false; + } + } return true; } - //Edit Player Speed - static bool HandleModifySpeedCommand(ChatHandler* handler, const char* args) + //Edit Player Aspeed + static bool HandleModifyASpeedCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - float Speed = (float)atof((char*)args); - - if (Speed > 50.0f || Speed < 0.1f) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + float allSpeed; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + if (CheckModifySpeed(handler, args, target, allSpeed, 0.1f, 50.0f)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_ASPEED, LANG_YOURS_ASPEED_CHANGED, allSpeed); + target->SetSpeedRate(MOVE_WALK, allSpeed); + target->SetSpeedRate(MOVE_RUN, allSpeed); + target->SetSpeedRate(MOVE_SWIM, allSpeed); + target->SetSpeedRate(MOVE_FLIGHT, allSpeed); + return true; } + return false; + } - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - std::string targetNameLink = handler->GetNameLink(target); - - if (target->IsInFlight()) + //Edit Player Speed + static bool HandleModifySpeedCommand(ChatHandler* handler, const char* args) + { + float Speed; + Player* target = handler->getSelectedPlayerOrSelf(); + if (CheckModifySpeed(handler, args, target, Speed, 0.1f, 50.0f)) { - handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str()); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_SPEED, LANG_YOURS_SPEED_CHANGED, Speed); + target->SetSpeedRate(MOVE_RUN, Speed); + return true; } - - handler->PSendSysMessage(LANG_YOU_CHANGE_SPEED, Speed, targetNameLink.c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_SPEED_CHANGED, handler->GetNameLink().c_str(), Speed); - - target->SetSpeed(MOVE_RUN, Speed, true); - - return true; + return false; } //Edit Player Swim Speed static bool HandleModifySwimCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - float Swim = (float)atof((char*)args); - - if (Swim > 50.0f || Swim < 0.1f) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + float swimSpeed; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + if (CheckModifySpeed(handler, args, target, swimSpeed, 0.1f, 50.0f)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; - } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - std::string targetNameLink = handler->GetNameLink(target); - - if (target->IsInFlight()) - { - handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str()); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_SWIM_SPEED, LANG_YOURS_SWIM_SPEED_CHANGED, swimSpeed); + target->SetSpeedRate(MOVE_SWIM, swimSpeed); + return true; } - - handler->PSendSysMessage(LANG_YOU_CHANGE_SWIM_SPEED, Swim, targetNameLink.c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_SWIM_SPEED_CHANGED, handler->GetNameLink().c_str(), Swim); - - target->SetSpeed(MOVE_SWIM, Swim, true); - - return true; + return false; } - //Edit Player Walk Speed + //Edit Player Backwards Walk Speed static bool HandleModifyBWalkCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - float BSpeed = (float)atof((char*)args); - - if (BSpeed > 50.0f || BSpeed < 0.1f) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + float backSpeed; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + if (CheckModifySpeed(handler, args, target, backSpeed, 0.1f, 50.0f)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; - } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - std::string targetNameLink = handler->GetNameLink(target); - - if (target->IsInFlight()) - { - handler->PSendSysMessage(LANG_CHAR_IN_FLIGHT, targetNameLink.c_str()); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_BACK_SPEED, LANG_YOURS_BACK_SPEED_CHANGED, backSpeed); + target->SetSpeedRate(MOVE_RUN_BACK, backSpeed); + return true; } - - handler->PSendSysMessage(LANG_YOU_CHANGE_BACK_SPEED, BSpeed, targetNameLink.c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_BACK_SPEED_CHANGED, handler->GetNameLink().c_str(), BSpeed); - - target->SetSpeed(MOVE_RUN_BACK, BSpeed, true); - - return true; + return false; } //Edit Player Fly static bool HandleModifyFlyCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - float FSpeed = (float)atof((char*)args); - - if (FSpeed > 50.0f || FSpeed < 0.1f) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + float flySpeed; Player* target = handler->getSelectedPlayerOrSelf(); - if (!target) + if (CheckModifySpeed(handler, args, target, flySpeed, 0.1f, 50.0f, false)) { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; + NotifyModification(handler, target, LANG_YOU_CHANGE_FLY_SPEED, LANG_YOURS_FLY_SPEED_CHANGED, flySpeed); + target->SetSpeedRate(MOVE_FLIGHT, flySpeed); + return true; } - - // check online security - if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) - return false; - - handler->PSendSysMessage(LANG_YOU_CHANGE_FLY_SPEED, FSpeed, handler->GetNameLink(target).c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_FLY_SPEED_CHANGED, handler->GetNameLink().c_str(), FSpeed); - - target->SetSpeed(MOVE_FLIGHT, FSpeed, true); - - return true; + return false; } //Edit Player or Creature Scale static bool HandleModifyScaleCommand(ChatHandler* handler, const char* args) { - if (!*args) - return false; - - float Scale = (float)atof((char*)args); - if (Scale > 10.0f || Scale < 0.1f) - { - handler->SendSysMessage(LANG_BAD_VALUE); - handler->SetSentErrorMessage(true); - return false; - } - + float Scale; Unit* target = handler->getSelectedUnit(); - if (!target) + if (CheckModifySpeed(handler, args, target, Scale, 0.1f, 10.0f, false)) { - handler->SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); - handler->SetSentErrorMessage(true); - return false; - } - - if (Player* player = target->ToPlayer()) - { - // check online security - if (handler->HasLowerSecurity(player, ObjectGuid::Empty)) - return false; - - handler->PSendSysMessage(LANG_YOU_CHANGE_SIZE, Scale, handler->GetNameLink(player).c_str()); - if (handler->needReportToTarget(player)) - ChatHandler(player->GetSession()).PSendSysMessage(LANG_YOURS_SIZE_CHANGED, handler->GetNameLink().c_str(), Scale); + NotifyModification(handler, target, LANG_YOU_CHANGE_SIZE, LANG_YOURS_SIZE_CHANGED, Scale); + target->SetObjectScale(Scale); + return true; } - - target->SetObjectScale(Scale); - - return true; + return false; } //Enable Player mount @@ -932,9 +731,7 @@ public: if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) return false; - handler->PSendSysMessage(LANG_YOU_GIVE_MOUNT, handler->GetNameLink(target).c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_MOUNT_GIVED, handler->GetNameLink().c_str()); + NotifyModification(handler, target, LANG_YOU_GIVE_MOUNT, LANG_MOUNT_GIVED); target->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); target->Mount(mId); @@ -988,10 +785,7 @@ public: TC_LOG_DEBUG("misc", handler->GetTrinityString(LANG_CURRENT_MONEY), targetMoney, moneyToAdd, newmoney); if (newmoney <= 0) { - handler->PSendSysMessage(LANG_YOU_TAKE_ALL_MONEY, handler->GetNameLink(target).c_str()); - if (handler->needReportToTarget(target)) - ChatHandler(target->GetSession()).PSendSysMessage(LANG_YOURS_ALL_MONEY_GONE, handler->GetNameLink().c_str()); - + NotifyModification(handler, target, LANG_YOU_TAKE_ALL_MONEY, LANG_YOURS_ALL_MONEY_GONE); target->SetMoney(0); } else @@ -1339,8 +1133,8 @@ public: } // Set gender - target->SetByteValue(UNIT_FIELD_BYTES_0, 2, gender); - target->SetByteValue(PLAYER_BYTES_3, 0, gender); + target->SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_GENDER, gender); + target->SetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_GENDER, gender); // Change display ID target->InitDisplayIds(); diff --git a/src/server/scripts/Commands/cs_npc.cpp b/src/server/scripts/Commands/cs_npc.cpp index fbd199b99db..38aa96a6a66 100644 --- a/src/server/scripts/Commands/cs_npc.cpp +++ b/src/server/scripts/Commands/cs_npc.cpp @@ -113,7 +113,7 @@ EnumName<UnitFlags> const unitFlags[MAX_UNIT_FLAGS] = { CREATE_NAMED_ENUM(UNIT_FLAG_SERVER_CONTROLLED), CREATE_NAMED_ENUM(UNIT_FLAG_NON_ATTACKABLE), - CREATE_NAMED_ENUM(UNIT_FLAG_DISABLE_MOVE), + CREATE_NAMED_ENUM(UNIT_FLAG_REMOVE_CLIENT_CONTROL), CREATE_NAMED_ENUM(UNIT_FLAG_PVP_ATTACKABLE), CREATE_NAMED_ENUM(UNIT_FLAG_RENAME), CREATE_NAMED_ENUM(UNIT_FLAG_PREPARATION), @@ -125,7 +125,7 @@ EnumName<UnitFlags> const unitFlags[MAX_UNIT_FLAGS] = CREATE_NAMED_ENUM(UNIT_FLAG_PET_IN_COMBAT), CREATE_NAMED_ENUM(UNIT_FLAG_PVP), CREATE_NAMED_ENUM(UNIT_FLAG_SILENCED), - CREATE_NAMED_ENUM(UNIT_FLAG_UNK_14), + CREATE_NAMED_ENUM(UNIT_FLAG_CANNOT_SWIM), CREATE_NAMED_ENUM(UNIT_FLAG_UNK_15), CREATE_NAMED_ENUM(UNIT_FLAG_UNK_16), CREATE_NAMED_ENUM(UNIT_FLAG_PACIFIED), @@ -220,14 +220,15 @@ public: { "whisper", rbac::RBAC_PERM_COMMAND_NPC_WHISPER, false, &HandleNpcWhisperCommand, "" }, { "yell", rbac::RBAC_PERM_COMMAND_NPC_YELL, false, &HandleNpcYellCommand, "" }, { "tame", rbac::RBAC_PERM_COMMAND_NPC_TAME, false, &HandleNpcTameCommand, "" }, - { "add", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, NULL, "", npcAddCommandTable }, - { "delete", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, NULL, "", npcDeleteCommandTable }, - { "follow", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, NULL, "", npcFollowCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_NPC_SET, false, NULL, "", npcSetCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, nullptr, "", npcAddCommandTable }, + { "delete", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, nullptr, "", npcDeleteCommandTable }, + { "follow", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, nullptr, "", npcFollowCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_NPC_SET, false, nullptr, "", npcSetCommandTable }, + { "evade", rbac::RBAC_PERM_COMMAND_NPC_EVADE, false, &HandleNpcEvadeCommand, "" }, }; static std::vector<ChatCommand> commandTable = { - { "npc", rbac::RBAC_PERM_COMMAND_NPC, false, NULL, "", npcCommandTable }, + { "npc", rbac::RBAC_PERM_COMMAND_NPC, false, nullptr, "", npcCommandTable }, }; return commandTable; } @@ -318,17 +319,17 @@ public: uint32 itemId = item_int; - char* fmaxcount = strtok(NULL, " "); //add maxcount, default: 0 + char* fmaxcount = strtok(nullptr, " "); //add maxcount, default: 0 uint32 maxcount = 0; if (fmaxcount) maxcount = atoul(fmaxcount); - char* fincrtime = strtok(NULL, " "); //add incrtime, default: 0 + char* fincrtime = strtok(nullptr, " "); //add incrtime, default: 0 uint32 incrtime = 0; if (fincrtime) incrtime = atoul(fincrtime); - char* fextendedcost = strtok(NULL, " "); //add ExtendedCost, default: 0 + char* fextendedcost = strtok(nullptr, " "); //add ExtendedCost, default: 0 uint32 extendedcost = fextendedcost ? atoul(fextendedcost) : 0; Creature* vendor = handler->getSelectedCreature(); if (!vendor) @@ -361,7 +362,7 @@ public: return false; char* guidStr = strtok((char*)args, " "); - char* waitStr = strtok((char*)NULL, " "); + char* waitStr = strtok((char*)nullptr, " "); ObjectGuid::LowType lowGuid = atoi((char*)guidStr); @@ -446,36 +447,24 @@ public: } Creature* creature = handler->getSelectedCreature(); - if (!creature) + if (!creature || creature->IsPet()) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } - if (creature->IsPet()) - { - if (((Pet*)creature)->getPetType() == HUNTER_PET) - { - creature->SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, sObjectMgr->GetXPForLevel(lvl)/4); - creature->SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); - } - ((Pet*)creature)->GivePetLevel(lvl); - } - else - { - creature->SetMaxHealth(100 + 30*lvl); - creature->SetHealth(100 + 30*lvl); - creature->SetLevel(lvl); - creature->SaveToDB(); - } + creature->SetMaxHealth(100 + 30*lvl); + creature->SetHealth(100 + 30*lvl); + creature->SetLevel(lvl); + creature->SaveToDB(); return true; } static bool HandleNpcDeleteCommand(ChatHandler* handler, char const* args) { - Creature* unit = NULL; + Creature* unit = nullptr; if (*args) { @@ -628,7 +617,7 @@ public: return false; char* arg1 = strtok((char*)args, " "); - char* arg2 = strtok((char*)NULL, ""); + char* arg2 = strtok((char*)nullptr, ""); if (!arg1 || !arg2) return false; @@ -926,8 +915,8 @@ public: // later switched on/off according to special events (like escort // quests, etc) char* guid_str = strtok((char*)args, " "); - char* type_str = strtok((char*)NULL, " "); - char* dontdel_str = strtok((char*)NULL, " "); + char* type_str = strtok((char*)nullptr, " "); + char* dontdel_str = strtok((char*)nullptr, " "); bool doNotDelete = false; @@ -935,7 +924,7 @@ public: return false; ObjectGuid::LowType lowguid = 0; - Creature* creature = NULL; + Creature* creature = nullptr; if (dontdel_str) { @@ -961,7 +950,7 @@ public: { //TC_LOG_ERROR("misc", "DEBUG: type_str, NODEL "); doNotDelete = true; - type_str = NULL; + type_str = nullptr; } } } @@ -1001,7 +990,7 @@ public: } // now lowguid is low guid really existed creature - // and creature point (maybe) to this creature or NULL + // and creature point (maybe) to this creature or nullptr MovementGeneratorType move_type; @@ -1260,7 +1249,7 @@ public: } char* receiver_str = strtok((char*)args, " "); - char* text = strtok(NULL, ""); + char* text = strtok(nullptr, ""); if (!receiver_str || !text) { @@ -1319,7 +1308,16 @@ public: if (!*args) return false; - char* charID = handler->extractKeyFromLink((char*)args, "Hcreature_entry"); + bool loot = false; + char const* spawntype_str = strtok((char*)args, " "); + char const* entry_str = strtok(nullptr, ""); + if (stricmp(spawntype_str, "LOOT") == 0) + loot = true; + else if (stricmp(spawntype_str, "NOLOOT") == 0) + loot = false; + else + entry_str = args; + char* charID = handler->extractKeyFromLink((char*)entry_str, "Hcreature_entry"); if (!charID) return false; @@ -1332,7 +1330,7 @@ public: if (!sObjectMgr->GetCreatureTemplate(id)) return false; - chr->SummonCreature(id, *chr, TEMPSUMMON_CORPSE_DESPAWN, 120); + chr->SummonCreature(id, *chr, loot ? TEMPSUMMON_CORPSE_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN, 30 * IN_MILLISECONDS); return true; } @@ -1404,6 +1402,51 @@ public: return true; } + static bool HandleNpcEvadeCommand(ChatHandler* handler, char const* args) + { + Creature* creatureTarget = handler->getSelectedCreature(); + if (!creatureTarget || creatureTarget->IsPet()) + { + handler->PSendSysMessage(LANG_SELECT_CREATURE); + handler->SetSentErrorMessage(true); + return false; + } + + if (!creatureTarget->IsAIEnabled) + { + handler->PSendSysMessage(LANG_CREATURE_NOT_AI_ENABLED); + handler->SetSentErrorMessage(true); + return false; + } + + char* type_str = args ? strtok((char*)args, " ") : nullptr; + char* force_str = args ? strtok(nullptr, " ") : nullptr; + + CreatureAI::EvadeReason why = CreatureAI::EVADE_REASON_OTHER; + bool force = false; + if (type_str) + { + if (stricmp(type_str, "NO_HOSTILES") == 0 || stricmp(type_str, "EVADE_REASON_NO_HOSTILES") == 0) + why = CreatureAI::EVADE_REASON_NO_HOSTILES; + else if (stricmp(type_str, "BOUNDARY") == 0 || stricmp(type_str, "EVADE_REASON_BOUNDARY") == 0) + why = CreatureAI::EVADE_REASON_BOUNDARY; + else if (stricmp(type_str, "SEQUENCE_BREAK") == 0 || stricmp(type_str, "EVADE_REASON_SEQUENCE_BREAK") == 0) + why = CreatureAI::EVADE_REASON_SEQUENCE_BREAK; + else if (stricmp(type_str, "FORCE") == 0) + force = true; + + if (!force && force_str) + if (stricmp(force_str, "FORCE") == 0) + force = true; + } + + if (force) + creatureTarget->ClearUnitState(UNIT_STATE_EVADE); + creatureTarget->AI()->EnterEvadeMode(why); + + return true; + } + static bool HandleNpcAddFormationCommand(ChatHandler* handler, char const* args) { if (!*args) @@ -1515,7 +1558,7 @@ public: if (!pSlotID) return false; - char* pItemID = strtok(NULL, " "); + char* pItemID = strtok(nullptr, " "); if (!pItemID) return false; diff --git a/src/server/scripts/Commands/cs_pet.cpp b/src/server/scripts/Commands/cs_pet.cpp index 4f0a179142d..a86de766117 100644 --- a/src/server/scripts/Commands/cs_pet.cpp +++ b/src/server/scripts/Commands/cs_pet.cpp @@ -22,6 +22,19 @@ #include "ObjectMgr.h" #include "ScriptMgr.h" +static inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) +{ + if (Unit* target = handler->getSelectedUnit()) + { + if (target->GetTypeId() == TYPEID_PLAYER) + return target->ToPlayer()->GetPet(); + if (target->IsPet()) + return target->ToPet(); + return nullptr; + } + Player* player = handler->GetSession()->GetPlayer(); + return player ? player->GetPet() : nullptr; +} class pet_commandscript : public CommandScript { public: @@ -34,6 +47,7 @@ public: { "create", rbac::RBAC_PERM_COMMAND_PET_CREATE, false, &HandlePetCreateCommand, "" }, { "learn", rbac::RBAC_PERM_COMMAND_PET_LEARN, false, &HandlePetLearnCommand, "" }, { "unlearn", rbac::RBAC_PERM_COMMAND_PET_UNLEARN, false, &HandlePetUnlearnCommand, "" }, + { "level", rbac::RBAC_PERM_COMMAND_PET_LEVEL, false, &HandlePetLevelCommand, "" }, }; static std::vector<ChatCommand> commandTable = @@ -54,11 +68,11 @@ public: return false; } - CreatureTemplate const* creatrueTemplate = creatureTarget->GetCreatureTemplate(); - // Creatures with family 0 crashes the server - if (!creatrueTemplate->family) + CreatureTemplate const* creatureTemplate = creatureTarget->GetCreatureTemplate(); + // Creatures with family CREATURE_FAMILY_NONE crashes the server + if (creatureTemplate->family == CREATURE_FAMILY_NONE) { - handler->PSendSysMessage("This creature cannot be tamed. (family id: 0)."); + handler->PSendSysMessage("This creature cannot be tamed. Family id: 0 (CREATURE_FAMILY_NONE)."); handler->SetSentErrorMessage(true); return false; } @@ -119,12 +133,11 @@ public: if (!*args) return false; - Player* player = handler->GetSession()->GetPlayer(); - Pet* pet = player->GetPet(); + Pet* pet = GetSelectedPlayerPetOrOwn(handler); if (!pet) { - handler->PSendSysMessage("You have no pet"); + handler->SendSysMessage(LANG_SELECT_PLAYER_OR_PET); handler->SetSentErrorMessage(true); return false; } @@ -162,11 +175,10 @@ public: if (!*args) return false; - Player* player = handler->GetSession()->GetPlayer(); - Pet* pet = player->GetPet(); + Pet* pet = GetSelectedPlayerPetOrOwn(handler); if (!pet) { - handler->PSendSysMessage("You have no pet"); + handler->SendSysMessage(LANG_SELECT_PLAYER_OR_PET); handler->SetSentErrorMessage(true); return false; } @@ -180,6 +192,37 @@ public: return true; } + + static bool HandlePetLevelCommand(ChatHandler* handler, char const* args) + { + Pet* pet = GetSelectedPlayerPetOrOwn(handler); + Player* owner = pet ? pet->GetOwner() : nullptr; + if (!pet || !owner) + { + handler->SendSysMessage(LANG_SELECT_PLAYER_OR_PET); + handler->SetSentErrorMessage(true); + return false; + } + + int32 level = args ? atoi(args) : 0; + if (level == 0) + level = owner->getLevel() - pet->getLevel(); + if (level == 0 || level < -STRONG_MAX_LEVEL || level > STRONG_MAX_LEVEL) + { + handler->SendSysMessage(LANG_BAD_VALUE); + handler->SetSentErrorMessage(true); + return false; + } + + int32 newLevel = pet->getLevel() + level; + if (newLevel < 1) + newLevel = 1; + else if (newLevel > owner->getLevel()) + newLevel = owner->getLevel(); + + pet->GivePetLevel(newLevel); + return true; + } }; void AddSC_pet_commandscript() diff --git a/src/server/scripts/Commands/cs_rbac.cpp b/src/server/scripts/Commands/cs_rbac.cpp index f7c2d21c12d..64692c4d0ed 100644 --- a/src/server/scripts/Commands/cs_rbac.cpp +++ b/src/server/scripts/Commands/cs_rbac.cpp @@ -49,7 +49,7 @@ class rbac_commandscript : public CommandScript public: rbac_commandscript() : CommandScript("rbac_commandscript") { } - std::vector<ChatCommand> GetCommands() const + std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> rbacAccountCommandTable = { @@ -139,7 +139,7 @@ public: { accountName = param1; - if (AccountMgr::normalizeString(accountName)) + if (Utf8ToUpperOnlyLatin(accountName)) accountId = AccountMgr::GetId(accountName); if (!accountId) @@ -157,7 +157,7 @@ public: if (!rdata) { - data->rbac = new rbac::RBACData(accountId, accountName, realmID, AccountMgr::GetSecurity(accountId, realmID)); + data->rbac = new rbac::RBACData(accountId, accountName, realm.Id.Realm, AccountMgr::GetSecurity(accountId, realm.Id.Realm)); data->rbac->LoadFromDB(); data->needDelete = true; } diff --git a/src/server/scripts/Commands/cs_reload.cpp b/src/server/scripts/Commands/cs_reload.cpp index 56b0dbf43d0..4470fa7de42 100644 --- a/src/server/scripts/Commands/cs_reload.cpp +++ b/src/server/scripts/Commands/cs_reload.cpp @@ -91,7 +91,7 @@ public: { "disenchant_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_DISENCHANT_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesDisenchantCommand, "" }, { "event_scripts", rbac::RBAC_PERM_COMMAND_RELOAD_EVENT_SCRIPTS, true, &HandleReloadEventScriptsCommand, "" }, { "fishing_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_FISHING_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesFishingCommand, "" }, - { "game_graveyard_zone", rbac::RBAC_PERM_COMMAND_RELOAD_GAME_GRAVEYARD_ZONE, true, &HandleReloadGameGraveyardZoneCommand, "" }, + { "graveyard_zone", rbac::RBAC_PERM_COMMAND_RELOAD_GRAVEYARD_ZONE, true, &HandleReloadGameGraveyardZoneCommand, "" }, { "game_tele", rbac::RBAC_PERM_COMMAND_RELOAD_GAME_TELE, true, &HandleReloadGameTeleCommand, "" }, { "gameobject_questender", rbac::RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUESTENDER, true, &HandleReloadGOQuestEnderCommand, "" }, { "gameobject_loot_template", rbac::RBAC_PERM_COMMAND_RELOAD_GAMEOBJECT_QUEST_LOOT_TEMPLATE, true, &HandleReloadLootTemplatesGameobjectCommand, "" }, @@ -251,7 +251,7 @@ public: static bool HandleReloadAllScriptsCommand(ChatHandler* handler, const char* /*args*/) { - if (sScriptMgr->IsScriptScheduled()) + if (sMapMgr->IsScriptScheduled()) { handler->PSendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); @@ -393,7 +393,7 @@ public: static bool HandleReloadCommandCommand(ChatHandler* handler, const char* /*args*/) { - handler->SetLoadCommandTable(true); + ChatHandler::invalidateCommandTable(); handler->SendGlobalGMSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } @@ -893,7 +893,7 @@ public: static bool HandleReloadEventScriptsCommand(ChatHandler* handler, const char* args) { - if (sScriptMgr->IsScriptScheduled()) + if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); @@ -913,7 +913,7 @@ public: static bool HandleReloadWpScriptsCommand(ChatHandler* handler, const char* args) { - if (sScriptMgr->IsScriptScheduled()) + if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); @@ -946,7 +946,7 @@ public: static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, const char* args) { - if (sScriptMgr->IsScriptScheduled()) + if (sMapMgr->IsScriptScheduled()) { handler->SendSysMessage("DB scripts used currently, please attempt reload later."); handler->SetSentErrorMessage(true); diff --git a/src/server/scripts/Commands/cs_reset.cpp b/src/server/scripts/Commands/cs_reset.cpp index 05941120423..ba1dab28350 100644 --- a/src/server/scripts/Commands/cs_reset.cpp +++ b/src/server/scripts/Commands/cs_reset.cpp @@ -102,7 +102,7 @@ public: player->setFactionForRace(player->getRace()); - player->SetUInt32Value(UNIT_FIELD_BYTES_0, ((player->getRace()) | (player->getClass() << 8) | (player->getGender() << 16) | (powerType << 24))); + player->SetByteValue(UNIT_FIELD_BYTES_0, UNIT_BYTES_0_OFFSET_POWER_TYPE, powerType); // reset only if player not in some form; if (player->GetShapeshiftForm() == FORM_NONE) diff --git a/src/server/scripts/Commands/cs_script_loader.cpp b/src/server/scripts/Commands/cs_script_loader.cpp new file mode 100644 index 00000000000..449e7053942 --- /dev/null +++ b/src/server/scripts/Commands/cs_script_loader.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_account_commandscript(); +void AddSC_achievement_commandscript(); +void AddSC_ahbot_commandscript(); +void AddSC_arena_commandscript(); +void AddSC_ban_commandscript(); +void AddSC_bf_commandscript(); +void AddSC_cast_commandscript(); +void AddSC_character_commandscript(); +void AddSC_cheat_commandscript(); +void AddSC_debug_commandscript(); +void AddSC_deserter_commandscript(); +void AddSC_disable_commandscript(); +void AddSC_event_commandscript(); +void AddSC_gm_commandscript(); +void AddSC_go_commandscript(); +void AddSC_gobject_commandscript(); +void AddSC_group_commandscript(); +void AddSC_guild_commandscript(); +void AddSC_honor_commandscript(); +void AddSC_instance_commandscript(); +void AddSC_learn_commandscript(); +void AddSC_lfg_commandscript(); +void AddSC_list_commandscript(); +void AddSC_lookup_commandscript(); +void AddSC_message_commandscript(); +void AddSC_misc_commandscript(); +void AddSC_mmaps_commandscript(); +void AddSC_modify_commandscript(); +void AddSC_npc_commandscript(); +void AddSC_pet_commandscript(); +void AddSC_quest_commandscript(); +void AddSC_rbac_commandscript(); +void AddSC_reload_commandscript(); +void AddSC_reset_commandscript(); +void AddSC_send_commandscript(); +void AddSC_server_commandscript(); +void AddSC_tele_commandscript(); +void AddSC_ticket_commandscript(); +void AddSC_titles_commandscript(); +void AddSC_wp_commandscript(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddCommandsScripts() +{ + AddSC_account_commandscript(); + AddSC_achievement_commandscript(); + AddSC_ahbot_commandscript(); + AddSC_arena_commandscript(); + AddSC_ban_commandscript(); + AddSC_bf_commandscript(); + AddSC_cast_commandscript(); + AddSC_character_commandscript(); + AddSC_cheat_commandscript(); + AddSC_debug_commandscript(); + AddSC_deserter_commandscript(); + AddSC_disable_commandscript(); + AddSC_event_commandscript(); + AddSC_gm_commandscript(); + AddSC_go_commandscript(); + AddSC_gobject_commandscript(); + AddSC_group_commandscript(); + AddSC_guild_commandscript(); + AddSC_honor_commandscript(); + AddSC_instance_commandscript(); + AddSC_learn_commandscript(); + AddSC_lookup_commandscript(); + AddSC_lfg_commandscript(); + AddSC_list_commandscript(); + AddSC_message_commandscript(); + AddSC_misc_commandscript(); + AddSC_mmaps_commandscript(); + AddSC_modify_commandscript(); + AddSC_npc_commandscript(); + AddSC_quest_commandscript(); + AddSC_pet_commandscript(); + AddSC_rbac_commandscript(); + AddSC_reload_commandscript(); + AddSC_reset_commandscript(); + AddSC_send_commandscript(); + AddSC_server_commandscript(); + AddSC_tele_commandscript(); + AddSC_ticket_commandscript(); + AddSC_titles_commandscript(); + AddSC_wp_commandscript(); +} diff --git a/src/server/scripts/Commands/cs_send.cpp b/src/server/scripts/Commands/cs_send.cpp index 672db3a3ab0..31544543426 100644 --- a/src/server/scripts/Commands/cs_send.cpp +++ b/src/server/scripts/Commands/cs_send.cpp @@ -74,7 +74,7 @@ public: std::string subject = msgSubject; std::string text = msgText; - // from console show not existed sender + // from console, use non-existing sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); /// @todo Fix poor design @@ -173,7 +173,7 @@ public: } } - // from console show not existed sender + // from console show nonexisting sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); // fill mail @@ -185,7 +185,7 @@ public: { if (Item* item = Item::CreateItem(itr->first, itr->second, handler->GetSession() ? handler->GetSession()->GetPlayer() : 0)) { - item->SaveToDB(trans); // save for prevent lost at next mail load, if send fail then item will deleted + item->SaveToDB(trans); // Save to prevent being lost at next mail load. If send fails, the item will be deleted. draft.AddItem(item); } } @@ -233,7 +233,7 @@ public: std::string subject = msgSubject; std::string text = msgText; - // from console show not existed sender + // from console show nonexisting sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); SQLTransaction trans = CharacterDatabase.BeginTransaction(); @@ -260,7 +260,7 @@ public: if (!msgStr) return false; - ///- Check that he is not logging out. + /// - Check if player is logging out. if (player->GetSession()->isLogingOut()) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); diff --git a/src/server/scripts/Commands/cs_server.cpp b/src/server/scripts/Commands/cs_server.cpp index 83bc2e47674..47239dba720 100644 --- a/src/server/scripts/Commands/cs_server.cpp +++ b/src/server/scripts/Commands/cs_server.cpp @@ -29,6 +29,7 @@ EndScriptData */ #include "Player.h" #include "ScriptMgr.h" #include "GitRevision.h" +#include "Util.h" class server_commandscript : public CommandScript { @@ -52,12 +53,14 @@ public: static std::vector<ChatCommand> serverRestartCommandTable = { { "cancel", rbac::RBAC_PERM_COMMAND_SERVER_RESTART_CANCEL, true, &HandleServerShutDownCancelCommand, "" }, + { "force", rbac::RBAC_PERM_COMMAND_SERVER_RESTART_FORCE, true, &HandleServerForceRestartCommand, "" }, { "" , rbac::RBAC_PERM_COMMAND_SERVER_RESTART, true, &HandleServerRestartCommand, "" }, }; static std::vector<ChatCommand> serverShutdownCommandTable = { { "cancel", rbac::RBAC_PERM_COMMAND_SERVER_SHUTDOWN_CANCEL, true, &HandleServerShutDownCancelCommand, "" }, + { "force", rbac::RBAC_PERM_COMMAND_SERVER_SHUTDOWN_FORCE, true, &HandleServerForceShutDownCommand, "" }, { "" , rbac::RBAC_PERM_COMMAND_SERVER_SHUTDOWN, true, &HandleServerShutDownCommand, "" }, }; @@ -73,19 +76,19 @@ public: { { "corpses", rbac::RBAC_PERM_COMMAND_SERVER_CORPSES, true, &HandleServerCorpsesCommand, "" }, { "exit", rbac::RBAC_PERM_COMMAND_SERVER_EXIT, true, &HandleServerExitCommand, "" }, - { "idlerestart", rbac::RBAC_PERM_COMMAND_SERVER_IDLERESTART, true, NULL, "", serverIdleRestartCommandTable }, - { "idleshutdown", rbac::RBAC_PERM_COMMAND_SERVER_IDLESHUTDOWN, true, NULL, "", serverIdleShutdownCommandTable }, + { "idlerestart", rbac::RBAC_PERM_COMMAND_SERVER_IDLERESTART, true, nullptr, "", serverIdleRestartCommandTable }, + { "idleshutdown", rbac::RBAC_PERM_COMMAND_SERVER_IDLESHUTDOWN, true, nullptr, "", serverIdleShutdownCommandTable }, { "info", rbac::RBAC_PERM_COMMAND_SERVER_INFO, true, &HandleServerInfoCommand, "" }, { "motd", rbac::RBAC_PERM_COMMAND_SERVER_MOTD, true, &HandleServerMotdCommand, "" }, { "plimit", rbac::RBAC_PERM_COMMAND_SERVER_PLIMIT, true, &HandleServerPLimitCommand, "" }, - { "restart", rbac::RBAC_PERM_COMMAND_SERVER_RESTART, true, NULL, "", serverRestartCommandTable }, - { "shutdown", rbac::RBAC_PERM_COMMAND_SERVER_SHUTDOWN, true, NULL, "", serverShutdownCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_SERVER_SET, true, NULL, "", serverSetCommandTable }, + { "restart", rbac::RBAC_PERM_COMMAND_SERVER_RESTART, true, nullptr, "", serverRestartCommandTable }, + { "shutdown", rbac::RBAC_PERM_COMMAND_SERVER_SHUTDOWN, true, nullptr, "", serverShutdownCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_SERVER_SET, true, nullptr, "", serverSetCommandTable }, }; static std::vector<ChatCommand> commandTable = { - { "server", rbac::RBAC_PERM_COMMAND_SERVER, true, NULL, "", serverCommandTable }, + { "server", rbac::RBAC_PERM_COMMAND_SERVER, true, nullptr, "", serverCommandTable }, }; return commandTable; } @@ -192,19 +195,34 @@ public: return true; } - static bool HandleServerShutDownCommand(ChatHandler* /*handler*/, char const* args) + static bool IsOnlyUser(WorldSession* mySession) { - return ShutdownServer(args, 0, SHUTDOWN_EXIT_CODE); + // check if there is any session connected from a different address + std::string myAddr = mySession ? mySession->GetRemoteAddress() : ""; + SessionMap const& sessions = sWorld->GetAllSessions(); + for (SessionMap::value_type const& session : sessions) + if (session.second && myAddr != session.second->GetRemoteAddress()) + return false; + return true; + } + static bool HandleServerShutDownCommand(ChatHandler* handler, char const* args) + { + return ShutdownServer(args, IsOnlyUser(handler->GetSession()) ? SHUTDOWN_MASK_FORCE : 0, SHUTDOWN_EXIT_CODE); } - static bool HandleServerRestartCommand(ChatHandler* /*handler*/, char const* args) + static bool HandleServerRestartCommand(ChatHandler* handler, char const* args) { - return ShutdownServer(args, SHUTDOWN_MASK_RESTART, RESTART_EXIT_CODE); + return ShutdownServer(args, IsOnlyUser(handler->GetSession()) ? (SHUTDOWN_MASK_FORCE | SHUTDOWN_MASK_RESTART) : SHUTDOWN_MASK_RESTART, RESTART_EXIT_CODE); } - static bool HandleServerIdleRestartCommand(ChatHandler* /*handler*/, char const* args) + static bool HandleServerForceShutDownCommand(ChatHandler* /*handler*/, char const* args) { - return ShutdownServer(args, SHUTDOWN_MASK_RESTART | SHUTDOWN_MASK_IDLE, RESTART_EXIT_CODE); + return ShutdownServer(args, SHUTDOWN_MASK_FORCE, SHUTDOWN_EXIT_CODE); + } + + static bool HandleServerForceRestartCommand(ChatHandler* /*handler*/, char const* args) + { + return ShutdownServer(args, SHUTDOWN_MASK_FORCE | SHUTDOWN_MASK_RESTART, RESTART_EXIT_CODE); } static bool HandleServerIdleShutDownCommand(ChatHandler* /*handler*/, char const* args) @@ -212,6 +230,11 @@ public: return ShutdownServer(args, SHUTDOWN_MASK_IDLE, SHUTDOWN_EXIT_CODE); } + static bool HandleServerIdleRestartCommand(ChatHandler* /*handler*/, char const* args) + { + return ShutdownServer(args, SHUTDOWN_MASK_RESTART | SHUTDOWN_MASK_IDLE, RESTART_EXIT_CODE); + } + // Exit the realm static bool HandleServerExitCommand(ChatHandler* handler, char const* /*args*/) { @@ -256,8 +279,8 @@ public: return false; char* type = strtok((char*)args, " "); - char* name = strtok(NULL, " "); - char* level = strtok(NULL, " "); + char* name = strtok(nullptr, " "); + char* level = strtok(nullptr, " "); if (!type || !name || !level || *name == '\0' || *level == '\0' || (*type != 'a' && *type != 'l')) return false; @@ -313,10 +336,26 @@ private: return false; // #delay [#exit_code] [reason] + int32 delay = 0; char* delayStr = strtok((char*)args, " "); - if (!delayStr || !isNumeric(delayStr)) + if (!delayStr) return false; + if (isNumeric(delayStr)) + { + delay = atoi(delayStr); + // Prevent interpret wrong arg value as 0 secs shutdown time + if ((delay == 0 && (delayStr[0] != '0' || delayStr[1] != '\0')) || delay < 0) + return false; + } + else + { + delay = TimeStringToSecs(std::string(delayStr)); + + if (delay == 0) + return false; + } + char* exitCodeStr = nullptr; char reason[256] = { 0 }; @@ -337,17 +376,15 @@ private: } } - int32 delay = atoi(delayStr); - - // Prevent interpret wrong arg value as 0 secs shutdown time - if ((delay == 0 && (delayStr[0] != '0' || delayStr[1] != '\0')) || delay < 0) - return false; - int32 exitCode = defaultExitCode; if (exitCodeStr) if (!ParseExitCode(exitCodeStr, exitCode)) return false; + // Override parameter "delay" with the configuration value if there are still players connected and "force" parameter was not specified + if (delay < (int32)sWorld->getIntConfig(CONFIG_FORCE_SHUTDOWN_THRESHOLD) && !(shutdownMask & SHUTDOWN_MASK_FORCE)) + delay = (int32)sWorld->getIntConfig(CONFIG_FORCE_SHUTDOWN_THRESHOLD); + sWorld->ShutdownServ(delay, shutdownMask, static_cast<uint8>(exitCode), std::string(reason)); return true; diff --git a/src/server/scripts/Commands/cs_ticket.cpp b/src/server/scripts/Commands/cs_ticket.cpp index c5c85f5f3cc..26f712eb8ef 100644 --- a/src/server/scripts/Commands/cs_ticket.cpp +++ b/src/server/scripts/Commands/cs_ticket.cpp @@ -95,7 +95,7 @@ public: ObjectGuid targetGuid = sObjectMgr->GetPlayerGUIDByName(target); uint32 accountId = sObjectMgr->GetPlayerAccountIdByGUID(targetGuid); // Target must exist and have administrative rights - if (!AccountMgr::HasPermission(accountId, rbac::RBAC_PERM_COMMANDS_BE_ASSIGNED_TICKET, realmID)) + if (!AccountMgr::HasPermission(accountId, rbac::RBAC_PERM_COMMANDS_BE_ASSIGNED_TICKET, realm.Id.Realm)) { handler->SendSysMessage(LANG_COMMAND_TICKETASSIGNERROR_A); return true; @@ -119,7 +119,7 @@ public: // Assign ticket SQLTransaction trans = SQLTransaction(NULL); - ticket->SetAssignedTo(targetGuid, AccountMgr::IsAdminAccount(AccountMgr::GetSecurity(accountId, realmID))); + ticket->SetAssignedTo(targetGuid, AccountMgr::IsAdminAccount(AccountMgr::GetSecurity(accountId, realm.Id.Realm))); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); @@ -199,7 +199,12 @@ public: ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, NULL, ticket->GetAssignedToName().c_str(), NULL, NULL, NULL); + std::string msg = [&] { + std::string const assignedName = ticket->GetAssignedToName(); + return ticket->FormatMessageString(*handler, nullptr, + assignedName.empty() ? nullptr : assignedName.c_str(), nullptr, nullptr, nullptr); + }(); + msg += handler->PGetParseString(LANG_COMMAND_TICKETLISTADDCOMMENT, player ? player->GetName().c_str() : "Console", comment); handler->SendGlobalGMSysMessage(msg.c_str()); @@ -387,7 +392,7 @@ public: { ObjectGuid guid = ticket->GetAssignedToGUID(); uint32 accountId = sObjectMgr->GetPlayerAccountIdByGUID(guid); - security = AccountMgr::GetSecurity(accountId, realmID); + security = AccountMgr::GetSecurity(accountId, realm.Id.Realm); } // Check security diff --git a/src/server/scripts/Commands/cs_titles.cpp b/src/server/scripts/Commands/cs_titles.cpp index 2f5d7b8364c..6309e7279c9 100644 --- a/src/server/scripts/Commands/cs_titles.cpp +++ b/src/server/scripts/Commands/cs_titles.cpp @@ -225,7 +225,7 @@ public: if (CharTitlesEntry const* tEntry = sCharTitlesStore.LookupEntry(i)) titles2 &= ~(uint64(1) << tEntry->bit_index); - titles &= ~titles2; // remove not existed titles + titles &= ~titles2; // remove non-existing titles target->SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES, titles); handler->SendSysMessage(LANG_DONE); diff --git a/src/server/scripts/Commands/cs_wp.cpp b/src/server/scripts/Commands/cs_wp.cpp index ef61c231104..424f94f7385 100644 --- a/src/server/scripts/Commands/cs_wp.cpp +++ b/src/server/scripts/Commands/cs_wp.cpp @@ -561,29 +561,24 @@ public: // -> variable lowguid is filled with the GUID of the NPC uint32 pathid = 0; uint32 point = 0; - uint32 wpGuid = 0; Creature* target = handler->getSelectedCreature(); PreparedStatement* stmt = NULL; + // User did select a visual waypoint? if (!target || target->GetEntry() != VISUAL_WAYPOINT) { handler->SendSysMessage("|cffff33ffERROR: You must select a waypoint.|r"); return false; } - // The visual waypoint - wpGuid = target->GetGUID().GetCounter(); - - // User did select a visual waypoint? - // Check the creature stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_WPGUID); - stmt->setUInt32(0, wpGuid); + stmt->setUInt32(0, target->GetSpawnId()); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) { - handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetGUID().GetCounter()); + handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDSEARCH, target->GetSpawnId()); // Select waypoint number from database // Since we compare float values, we have to deal with // some difficulties. @@ -599,11 +594,11 @@ public: stmt->setString(3, maxDiff); stmt->setFloat(4, target->GetPositionZ()); stmt->setString(5, maxDiff); - PreparedQueryResult queryResult = WorldDatabase.Query(stmt); + result = WorldDatabase.Query(stmt); - if (!queryResult) + if (!result) { - handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, wpGuid); + handler->PSendSysMessage(LANG_WAYPOINT_NOTFOUNDDBPROBLEM, target->GetSpawnId()); return true; } } @@ -631,13 +626,8 @@ public: { handler->PSendSysMessage("|cff00ff00DEBUG: wp modify del, PathID: |r|cff00ffff%u|r", pathid); - if (wpGuid != 0) - if (Creature* wpCreature = handler->GetSession()->GetPlayer()->GetMap()->GetCreature(ObjectGuid(HighGuid::Unit, VISUAL_WAYPOINT, wpGuid))) - { - wpCreature->CombatStop(); - wpCreature->DeleteFromDB(); - wpCreature->AddObjectToRemoveList(); - } + target->DeleteFromDB(); + target->AddObjectToRemoveList(); stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_DATA); stmt->setUInt32(0, pathid); @@ -659,51 +649,40 @@ public: Player* chr = handler->GetSession()->GetPlayer(); Map* map = chr->GetMap(); + // What to do: + // Move the visual spawnpoint + // Respawn the owner of the waypoints + target->DeleteFromDB(); + target->AddObjectToRemoveList(); + + // re-create + Creature* wpCreature = new Creature(); + if (!wpCreature->Create(map->GenerateLowGuid<HighGuid::Unit>(), map, chr->GetPhaseMaskForSpawn(), VISUAL_WAYPOINT, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation())) { - // What to do: - // Move the visual spawnpoint - // Respawn the owner of the waypoints - if (wpGuid != 0) - { - if (Creature* wpCreature = map->GetCreature(ObjectGuid(HighGuid::Unit, VISUAL_WAYPOINT, wpGuid))) - { - wpCreature->CombatStop(); - wpCreature->DeleteFromDB(); - wpCreature->AddObjectToRemoveList(); - } - // re-create - Creature* wpCreature2 = new Creature(); - if (!wpCreature2->Create(map->GenerateLowGuid<HighGuid::Unit>(), map, chr->GetPhaseMaskForSpawn(), VISUAL_WAYPOINT, chr->GetPositionX(), chr->GetPositionY(), chr->GetPositionZ(), chr->GetOrientation())) - { - handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT); - delete wpCreature2; - wpCreature2 = NULL; - return false; - } + handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT); + delete wpCreature; + return false; + } - wpCreature2->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn()); - // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells(); - /// @todo Should we first use "Create" then use "LoadFromDB"? - if (!wpCreature2->LoadCreatureFromDB(wpCreature2->GetSpawnId(), map)) - { - handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT); - delete wpCreature2; - wpCreature2 = NULL; - return false; - } - //sMapMgr->GetMap(npcCreature->GetMapId())->Add(wpCreature2); - } + wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn()); + // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells(); + /// @todo Should we first use "Create" then use "LoadFromDB"? + if (!wpCreature->LoadCreatureFromDB(wpCreature->GetSpawnId(), map)) + { + handler->PSendSysMessage(LANG_WAYPOINT_VP_NOTCREATED, VISUAL_WAYPOINT); + delete wpCreature; + return false; + } - stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_POSITION); - stmt->setFloat(0, chr->GetPositionX()); - stmt->setFloat(1, chr->GetPositionY()); - stmt->setFloat(2, chr->GetPositionZ()); - stmt->setUInt32(3, pathid); - stmt->setUInt32(4, point); - WorldDatabase.Execute(stmt); + stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_POSITION); + stmt->setFloat(0, chr->GetPositionX()); + stmt->setFloat(1, chr->GetPositionY()); + stmt->setFloat(2, chr->GetPositionZ()); + stmt->setUInt32(3, pathid); + stmt->setUInt32(4, point); + WorldDatabase.Execute(stmt); - handler->PSendSysMessage(LANG_WAYPOINT_CHANGED); - } + handler->PSendSysMessage(LANG_WAYPOINT_CHANGED); return true; } // move @@ -897,14 +876,15 @@ public: return false; } + wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn()); + // Set "wpguid" column to the visual waypoint stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_WPGUID); - stmt->setInt32(0, int32(wpCreature->GetGUID().GetCounter())); + stmt->setInt32(0, int32(wpCreature->GetSpawnId())); stmt->setUInt32(1, pathid); stmt->setUInt32(2, point); WorldDatabase.Execute(stmt); - wpCreature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn()); // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells(); if (!wpCreature->LoadCreatureFromDB(wpCreature->GetSpawnId(), map)) { diff --git a/src/server/scripts/Custom/CMakeLists.txt b/src/server/scripts/Custom/CMakeLists.txt deleted file mode 100644 index 595ff801813..00000000000 --- a/src/server/scripts/Custom/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -# file(GLOB_RECURSE sources_Custom Custom/*.cpp Custom/*.h) - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} -# ${sources_Custom} -) - -message(" -> Prepared: Custom") diff --git a/src/server/scripts/Custom/custom_script_loader.cpp b/src/server/scripts/Custom/custom_script_loader.cpp new file mode 100644 index 00000000000..dd4b5e99d77 --- /dev/null +++ b/src/server/scripts/Custom/custom_script_loader.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: + + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddCustomScripts() +{ +} diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp index 9cd724e5596..7b07c9272da 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp @@ -415,112 +415,12 @@ public: }; }; -// npc_kharan_mighthammer -enum KharamQuests -{ - QUEST_4001 = 4001, - QUEST_4342 = 4342 -}; - -#define GOSSIP_ITEM_KHARAN_1 "I need to know where the princess are, Kharan!" -#define GOSSIP_ITEM_KHARAN_2 "All is not lost, Kharan!" -#define GOSSIP_ITEM_KHARAN_3 "Gor'shak is my friend, you can trust me." -#define GOSSIP_ITEM_KHARAN_4 "Not enough, you need to tell me more." -#define GOSSIP_ITEM_KHARAN_5 "So what happened?" -#define GOSSIP_ITEM_KHARAN_6 "Continue..." -#define GOSSIP_ITEM_KHARAN_7 "So you suspect that someone on the inside was involved? That they were tipped off?" -#define GOSSIP_ITEM_KHARAN_8 "Continue with your story please." -#define GOSSIP_ITEM_KHARAN_9 "Indeed." -#define GOSSIP_ITEM_KHARAN_10 "The door is open, Kharan. You are a free man." - -class npc_kharan_mighthammer : public CreatureScript -{ -public: - npc_kharan_mighthammer() : CreatureScript("npc_kharan_mighthammer") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - player->SEND_GOSSIP_MENU(2475, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - player->SEND_GOSSIP_MENU(2476, creature->GetGUID()); - break; - - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); - player->SEND_GOSSIP_MENU(2477, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); - player->SEND_GOSSIP_MENU(2478, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_7, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+6); - player->SEND_GOSSIP_MENU(2479, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+6: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_8, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+7); - player->SEND_GOSSIP_MENU(2480, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+7: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_9, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+8); - player->SEND_GOSSIP_MENU(2481, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+8: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_10, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+9); - player->SEND_GOSSIP_MENU(2482, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+9: - player->CLOSE_GOSSIP_MENU(); - if (player->GetTeam() == HORDE) - player->AreaExploredOrEventHappens(QUEST_4001); - else - player->AreaExploredOrEventHappens(QUEST_4342); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_4001) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - if (player->GetQuestStatus(4342) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KHARAN_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - - if (player->GetTeam() == HORDE) - player->SEND_GOSSIP_MENU(2473, creature->GetGUID()); - else - player->SEND_GOSSIP_MENU(2474, creature->GetGUID()); - - return true; - } -}; - // npc_lokhtos_darkbargainer -enum LokhtosItems +enum Lokhtos { + QUEST_A_BINDING_CONTRACT = 7604, + ITEM_SULFURON_INGOT = 17203, ITEM_THRORIUM_BROTHERHOOD_CONTRACT = 18628, - ITEM_SULFURON_INGOT = 17203 -}; - -enum LokhtosQuests -{ - QUEST_A_BINDING_CONTRACT = 7604 -}; - -enum LokhtosSpells -{ SPELL_CREATE_THORIUM_BROTHERHOOD_CONTRACT_DND = 23059 }; @@ -570,67 +470,12 @@ public: } }; -// npc_dughal_stormwing -enum DughalQuests -{ - QUEST_JAIL_BREAK = 4322 -}; - -#define SAY_DUGHAL_FREE "Thank you, $N! I'm free!!!" -#define GOSSIP_DUGHAL "You're free, Dughal! Get out of here!" - -// npc_marshal_windsor -#define SAY_WINDSOR_AGGRO1 "You locked up the wrong Marshal. Prepare to be destroyed!" -#define SAY_WINDSOR_AGGRO2 "I bet you're sorry now, aren't you !?!!" -#define SAY_WINDSOR_AGGRO3 "You better hold me back $N or they are going to feel some prison house beatings." -#define SAY_WINDSOR_1 "Let's get a move on. My gear should be in the storage area up this way..." -#define SAY_WINDSOR_4_1 "Check that cell, $N. If someone is alive in there, we need to get them out." -#define SAY_WINDSOR_4_2 "Get him out of there!" -#define SAY_WINDSOR_4_3 "Good work! We're almost there, $N. This way." -#define SAY_WINDSOR_6 "This is it, $N. My stuff should be in that room. Cover me, I'm going in!" -#define SAY_WINDSOR_9 "Ah, there it is!" - -enum MarshalWindsor -{ - NPC_REGINALD_WINDSOR = 9682 -}; - -// npc_marshal_reginald_windsor -#define SAY_REGINALD_WINDSOR_0_1 "Can you feel the power, $N??? It's time to ROCK!" -#define SAY_REGINALD_WINDSOR_0_2 "Now we just have to free Tobias and we can get out of here. This way!" -#define SAY_REGINALD_WINDSOR_5_1 "Open it." -#define SAY_REGINALD_WINDSOR_5_2 "I never did like those two. Let's get moving." -#define SAY_REGINALD_WINDSOR_7_1 "Open it and be careful this time!" -#define SAY_REGINALD_WINDSOR_7_2 "That intolerant dirtbag finally got what was coming to him. Good riddance!" -#define SAY_REGINALD_WINDSOR_7_3 "Alright, let's go." -#define SAY_REGINALD_WINDSOR_13_1 "Open it. We need to hurry up. I can smell those Dark Irons coming a mile away and I can tell you one thing, they're COMING!" -#define SAY_REGINALD_WINDSOR_13_2 "Administering fists of fury on Crest Killer!" -#define SAY_REGINALD_WINDSOR_13_3 "He has to be in the last cell. Unless... they killed him." -#define SAY_REGINALD_WINDSOR_14_1 "Get him out of there!" -#define SAY_REGINALD_WINDSOR_14_2 "Excellent work, $N. Let's find the exit. I think I know the way. Follow me!" -#define SAY_REGINALD_WINDSOR_20_1 "We made it!" -#define SAY_REGINALD_WINDSOR_20_2 "Meet me at Maxwell's encampment. We'll go over the next stages of the plan there and figure out a way to decode my tablets without the decryption ring." - -enum MarshalReginaldWindor -{ - NPC_SHILL_DINGER = 9678, - NPC_CREST_KILLER = 9680 -}; - // npc_rocknot -enum RocknotSays -{ - SAY_GOT_BEER = 0 -}; - -enum RocknotSpells -{ - SPELL_DRUNKEN_RAGE = 14872 -}; - -enum RocknotQuests +enum Rocknot { - QUEST_ALE = 4295 + SAY_GOT_BEER = 0, + QUEST_ALE = 4295, + SPELL_DRUNKEN_RAGE = 14872 }; class npc_rocknot : public CreatureScript @@ -771,7 +616,6 @@ void AddSC_blackrock_depths() new at_ring_of_law(); new npc_grimstone(); new npc_phalanx(); - new npc_kharan_mighthammer(); new npc_lokhtos_darkbargainer(); new npc_rocknot(); } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp index 817aaf0a253..f962a019da6 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp @@ -187,6 +187,12 @@ public: events.ScheduleEvent(EVENT_MORTAL_STRIKE, urand(17000, 19000)); } + void IsSummonedBy(Unit* /*summoner*/) override + { + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); + DoZoneInCombat(); + } + void JustDied(Unit* /*killer*/) override { _JustDied(); diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp index 4a6fee12098..995fc44abd0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp @@ -206,9 +206,10 @@ public: Talk(SAY_GAMESBEGIN_2); me->setFaction(103); - me->SetUInt32Value(UNIT_NPC_FLAGS, 0); + me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); DoCast(me, SPELL_NEFARIANS_BARRIER); me->SetStandState(UNIT_STAND_STATE_STAND); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); AttackStart(target); events.ScheduleEvent(EVENT_SHADOW_BOLT, urand(3000, 10000)); events.ScheduleEvent(EVENT_FEAR, urand(10000, 20000)); diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp index e58bded801b..e97b7cba388 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp @@ -32,6 +32,7 @@ enum Say enum Spells { + // @todo orb uses the wrong spell, this needs sniffs SPELL_MINDCONTROL = 42013, SPELL_CHANNEL = 45537, SPELL_EGG_DESTROY = 19873, @@ -103,7 +104,7 @@ public: secondPhase = true; me->RemoveAllAuras(); - me->SetHealth(me->GetMaxHealth()); + me->SetFullHealth(); } void DoAction(int32 action) override @@ -114,6 +115,7 @@ public: void DamageTaken(Unit* /*who*/, uint32& damage) override { + // @todo this is wrong - razorgore should still take damage, he should just nuke the whole room and respawn if he dies during P1 if (!secondPhase) damage = 0; } @@ -146,6 +148,7 @@ public: break; case EVENT_CONFLAGRATION: DoCastVictim(SPELL_CONFLAGRATION); + // @todo is this even necessary? pretty sure AI ignores targets with disorient by default if (me->GetVictim() && me->EnsureVictim()->HasAura(SPELL_CONFLAGRATION)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true)) me->TauntApply(target); @@ -175,10 +178,10 @@ public: { if (InstanceScript* instance = go->GetInstanceScript()) if (instance->GetData(DATA_EGG_EVENT) != DONE) - if (Creature* razor = instance->GetCreature(DATA_RAZORGORE_THE_UNTAMED)) + if (Creature* razorgore = instance->GetCreature(DATA_RAZORGORE_THE_UNTAMED)) { - razor->Attack(player, true); - player->CastSpell(razor, SPELL_MINDCONTROL); + razorgore->Attack(player, true); + player->CastSpell(razorgore, SPELL_MINDCONTROL); } return true; } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp index 51bb314968d..ffec32c0619 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp @@ -27,6 +27,8 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "molten_core.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Emotes { @@ -36,9 +38,10 @@ enum Emotes enum Spells { SPELL_INFERNO = 19695, + SPELL_INFERNO_DMG = 19698, SPELL_IGNITE_MANA = 19659, SPELL_LIVING_BOMB = 20475, - SPELL_ARMAGEDDON = 20479, + SPELL_ARMAGEDDON = 20478, }; enum Events @@ -119,7 +122,36 @@ class boss_baron_geddon : public CreatureScript } }; +class spell_baron_geddon_inferno : public SpellScriptLoader +{ + public: + spell_baron_geddon_inferno() : SpellScriptLoader("spell_baron_geddon_inferno") { } + + class spell_baron_geddon_inferno_AuraScript : public AuraScript + { + PrepareAuraScript(spell_baron_geddon_inferno_AuraScript); + + void OnPeriodic(AuraEffect const* aurEff) + { + PreventDefaultAction(); + int32 damageForTick[8] = { 500, 500, 1000, 1000, 2000, 2000, 3000, 5000 }; + GetTarget()->CastCustomSpell(SPELL_INFERNO_DMG, SPELLVALUE_BASE_POINT0, damageForTick[aurEff->GetTickNumber() - 1], (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_baron_geddon_inferno_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_baron_geddon_inferno_AuraScript(); + } +}; + void AddSC_boss_baron_geddon() { new boss_baron_geddon(); + new spell_baron_geddon_inferno(); } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp index 9b487f7b5f9..8cff67d9f28 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp @@ -44,16 +44,20 @@ enum Texts enum Spells { - SPELL_MAGIC_REFLECTION = 20619, - SPELL_DAMAGE_REFLECTION = 21075, + SPELL_SUMMON_RAGNAROS = 19774, SPELL_BLAST_WAVE = 20229, - SPELL_AEGIS_OF_RAGNAROS = 20620, SPELL_TELEPORT = 20618, - SPELL_SUMMON_RAGNAROS = 19774, + SPELL_MAGIC_REFLECTION = 20619, + SPELL_AEGIS_OF_RAGNAROS = 20620, + SPELL_DAMAGE_REFLECTION = 21075 }; -#define GOSSIP_HELLO 4995 -#define GOSSIP_SELECT "Tell me more." +enum Extras +{ + OPTION_ID_YOU_CHALLENGED_US = 0, + FACTION_FRIENDLY = 35, + MENU_OPTION_YOU_CHALLENGED_US = 4108 +}; enum Events { @@ -64,7 +68,7 @@ enum Events EVENT_OUTRO_1 = 5, EVENT_OUTRO_2 = 6, - EVENT_OUTRO_3 = 7, + EVENT_OUTRO_3 = 7 }; class boss_majordomo : public CreatureScript @@ -106,7 +110,7 @@ class boss_majordomo : public CreatureScript if (!me->FindNearestCreature(NPC_FLAMEWAKER_HEALER, 100.0f) && !me->FindNearestCreature(NPC_FLAMEWAKER_ELITE, 100.0f)) { instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, me->GetEntry(), me); - me->setFaction(35); + me->setFaction(FACTION_FRIENDLY); EnterEvadeMode(); Talk(SAY_DEFEAT); _JustDied(); @@ -184,25 +188,20 @@ class boss_majordomo : public CreatureScript } else if (action == ACTION_START_RAGNAROS_ALT) { - me->setFaction(35); + me->setFaction(FACTION_FRIENDLY); me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); } } - }; - bool OnGossipHello(Player* player, Creature* creature) override - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(GOSSIP_HELLO, creature->GetGUID()); - return true; - } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 /*action*/) override - { - player->CLOSE_GOSSIP_MENU(); - creature->AI()->DoAction(ACTION_START_RAGNAROS); - return true; - } + void sGossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override + { + if (menuId == MENU_OPTION_YOU_CHALLENGED_US && gossipListId == OPTION_ID_YOU_CHALLENGED_US) + { + player->CLOSE_GOSSIP_MENU(); + DoAction(ACTION_START_RAGNAROS); + } + } + }; CreatureAI* GetAI(Creature* creature) const override { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp index e0cae87051f..a89a6b491e8 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp @@ -159,7 +159,7 @@ class boss_ragnaros : public CreatureScript break; case EVENT_INTRO_5: me->SetReactState(REACT_AGGRESSIVE); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); _introState = 2; break; default: diff --git a/src/server/scripts/EasternKingdoms/CMakeLists.txt b/src/server/scripts/EasternKingdoms/CMakeLists.txt deleted file mode 100644 index 8e6616347f9..00000000000 --- a/src/server/scripts/EasternKingdoms/CMakeLists.txt +++ /dev/null @@ -1,204 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - EasternKingdoms/zone_ghostlands.cpp - EasternKingdoms/AlteracValley/boss_galvangar.cpp - EasternKingdoms/AlteracValley/boss_balinda.cpp - EasternKingdoms/AlteracValley/boss_drekthar.cpp - EasternKingdoms/AlteracValley/boss_vanndar.cpp - EasternKingdoms/AlteracValley/alterac_valley.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_high_interrogator_gerstahn.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_general_angerforge.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_ambassador_flamelash.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_moira_bronzebeard.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp - EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp - EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_drakkisath.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_warmaster_voone.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_mother_smolderweb.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_quartermaster_zigris.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_halycon.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_highlord_omokk.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_the_beast.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_urok_doomhowl.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp - EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h - EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_gehennas.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_lucifron.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_garr.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h - EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_sulfuron_harbinger.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_magmadar.cpp - EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp - EasternKingdoms/Scholomance/boss_the_ravenian.cpp - EasternKingdoms/Scholomance/boss_instructor_malicia.cpp - EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp - EasternKingdoms/Scholomance/boss_illucia_barov.cpp - EasternKingdoms/Scholomance/scholomance.h - EasternKingdoms/Scholomance/boss_vectus.cpp - EasternKingdoms/Scholomance/boss_jandice_barov.cpp - EasternKingdoms/Scholomance/boss_kormok.cpp - EasternKingdoms/Scholomance/boss_lord_alexei_barov.cpp - EasternKingdoms/Scholomance/boss_doctor_theolen_krastinov.cpp - EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp - EasternKingdoms/Scholomance/instance_scholomance.cpp - EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp - EasternKingdoms/Scholomance/boss_ras_frostwhisper.cpp - EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp - EasternKingdoms/zone_isle_of_queldanas.cpp - EasternKingdoms/ZulGurub/boss_hakkar.cpp - EasternKingdoms/ZulGurub/boss_mandokir.cpp - EasternKingdoms/ZulGurub/boss_marli.cpp - EasternKingdoms/ZulGurub/boss_hazzarah.cpp - EasternKingdoms/ZulGurub/boss_jeklik.cpp - EasternKingdoms/ZulGurub/boss_grilek.cpp - EasternKingdoms/ZulGurub/zulgurub.h - EasternKingdoms/ZulGurub/boss_renataki.cpp - EasternKingdoms/ZulGurub/boss_arlokk.cpp - EasternKingdoms/ZulGurub/boss_gahzranka.cpp - EasternKingdoms/ZulGurub/boss_venoxis.cpp - EasternKingdoms/ZulGurub/instance_zulgurub.cpp - EasternKingdoms/ZulGurub/boss_jindo.cpp - EasternKingdoms/ZulGurub/boss_wushoolay.cpp - EasternKingdoms/ZulGurub/boss_thekal.cpp - EasternKingdoms/zone_wetlands.cpp - EasternKingdoms/zone_arathi_highlands.cpp - EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp - EasternKingdoms/Gnomeregan/gnomeregan.cpp - EasternKingdoms/Gnomeregan/gnomeregan.h - EasternKingdoms/zone_redridge_mountains.cpp - EasternKingdoms/ScarletEnclave/chapter2.cpp - EasternKingdoms/ScarletEnclave/chapter5.cpp - EasternKingdoms/ScarletEnclave/chapter1.cpp - EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp - EasternKingdoms/zone_eastern_plaguelands.cpp - EasternKingdoms/Stratholme/boss_baroness_anastari.cpp - EasternKingdoms/Stratholme/boss_nerubenkan.cpp - EasternKingdoms/Stratholme/instance_stratholme.cpp - EasternKingdoms/Stratholme/boss_dathrohan_balnazzar.cpp - EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp - EasternKingdoms/Stratholme/boss_baron_rivendare.cpp - EasternKingdoms/Stratholme/boss_magistrate_barthilas.cpp - EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp - EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp - EasternKingdoms/Stratholme/boss_cannon_master_willey.cpp - EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp - EasternKingdoms/Stratholme/boss_postmaster_malown.cpp - EasternKingdoms/Stratholme/stratholme.h - EasternKingdoms/Stratholme/stratholme.cpp - EasternKingdoms/zone_tirisfal_glades.cpp - EasternKingdoms/SunkenTemple/sunken_temple.cpp - EasternKingdoms/SunkenTemple/sunken_temple.h - EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp - EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp - EasternKingdoms/MagistersTerrace/magisters_terrace.h - EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp - EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp - EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp - EasternKingdoms/MagistersTerrace/boss_vexallus.cpp - EasternKingdoms/MagistersTerrace/magisters_terrace.cpp - EasternKingdoms/Uldaman/uldaman.cpp - EasternKingdoms/Uldaman/boss_ironaya.cpp - EasternKingdoms/Uldaman/uldaman.h - EasternKingdoms/Uldaman/instance_uldaman.cpp - EasternKingdoms/Uldaman/boss_archaedas.cpp - EasternKingdoms/zone_swamp_of_sorrows.cpp - EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp - EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp - EasternKingdoms/SunwellPlateau/sunwell_plateau.h - EasternKingdoms/SunwellPlateau/boss_muru.cpp - EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp - EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp - EasternKingdoms/SunwellPlateau/boss_brutallus.cpp - EasternKingdoms/SunwellPlateau/sunwell_plateau.cpp - EasternKingdoms/SunwellPlateau/boss_felmyst.cpp - EasternKingdoms/zone_stranglethorn_vale.cpp - EasternKingdoms/Deadmines/deadmines.h - EasternKingdoms/Deadmines/deadmines.cpp - EasternKingdoms/Deadmines/boss_mr_smite.cpp - EasternKingdoms/Deadmines/instance_deadmines.cpp - EasternKingdoms/zone_duskwood.cpp - EasternKingdoms/ScarletMonastery/boss_azshir_the_sleepless.cpp - EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp - EasternKingdoms/ScarletMonastery/boss_bloodmage_thalnos.cpp - EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp - EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp - EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp - EasternKingdoms/ScarletMonastery/boss_houndmaster_loksey.cpp - EasternKingdoms/ScarletMonastery/scarlet_monastery.h - EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp - EasternKingdoms/ScarletMonastery/boss_arcanist_doan.cpp - EasternKingdoms/ScarletMonastery/boss_herod.cpp - EasternKingdoms/ScarletMonastery/boss_scorn.cpp - EasternKingdoms/zone_undercity.cpp - EasternKingdoms/zone_loch_modan.cpp - EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp - EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp - EasternKingdoms/ShadowfangKeep/shadowfang_keep.h - EasternKingdoms/zone_burning_steppes.cpp - EasternKingdoms/zone_blasted_lands.cpp - EasternKingdoms/zone_stormwind_city.cpp - EasternKingdoms/ZulAman/boss_halazzi.cpp - EasternKingdoms/ZulAman/boss_hexlord.cpp - EasternKingdoms/ZulAman/boss_zuljin.cpp - EasternKingdoms/ZulAman/boss_akilzon.cpp - EasternKingdoms/ZulAman/instance_zulaman.cpp - EasternKingdoms/ZulAman/boss_janalai.cpp - EasternKingdoms/ZulAman/boss_nalorakk.cpp - EasternKingdoms/ZulAman/zulaman.cpp - EasternKingdoms/ZulAman/zulaman.h - EasternKingdoms/zone_hinterlands.cpp - EasternKingdoms/zone_western_plaguelands.cpp - EasternKingdoms/zone_silverpine_forest.cpp - EasternKingdoms/Karazhan/instance_karazhan.cpp - EasternKingdoms/Karazhan/boss_nightbane.cpp - EasternKingdoms/Karazhan/karazhan.cpp - EasternKingdoms/Karazhan/boss_curator.cpp - EasternKingdoms/Karazhan/boss_shade_of_aran.cpp - EasternKingdoms/Karazhan/boss_netherspite.cpp - EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp - EasternKingdoms/Karazhan/boss_midnight.cpp - EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp - EasternKingdoms/Karazhan/bosses_opera.cpp - EasternKingdoms/Karazhan/boss_moroes.cpp - EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp - EasternKingdoms/Karazhan/karazhan.h - EasternKingdoms/TheStockade/instance_the_stockade.cpp -) - -message(" -> Prepared: Eastern Kingdoms") diff --git a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp index 541ddc0e1c8..8f246ab9bf0 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp @@ -25,17 +25,25 @@ EndScriptData */ #include "ScriptedCreature.h" #include "deadmines.h" -enum Spels +enum Spells { SPELL_TRASH = 3391, SPELL_SMITE_STOMP = 6432, SPELL_SMITE_SLAM = 6435, - SPELL_NIMBLE_REFLEXES = 6264, + SPELL_NIMBLE_REFLEXES = 6264 +}; +enum Equips +{ EQUIP_SWORD = 5191, - EQUIP_MACE = 7230, + EQUIP_AXE = 5196, + EQUIP_MACE = 7230 +}; - SAY_AGGRO = 0, +enum Texts +{ + SAY_PHASE_1 = 2, + SAY_PHASE_2 = 3 }; class boss_mr_smite : public CreatureScript @@ -66,6 +74,8 @@ public: uiPhase = 0; uiTimer = 0; + + uiIsMoving = false; } InstanceScript* instance; @@ -79,16 +89,19 @@ public: uint32 uiPhase; uint32 uiTimer; + bool uiIsMoving; + void Reset() override { Initialize(); SetEquipmentSlots(false, EQUIP_SWORD, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); + me->SetStandState(UNIT_STAND_STATE_STAND); + me->SetReactState(REACT_AGGRESSIVE); } void EnterCombat(Unit* /*who*/) override { - Talk(SAY_AGGRO); } bool bCheckChances() @@ -105,38 +118,52 @@ public: if (!UpdateVictim()) return; - /*START ACID-AI*/ - if (uiTrashTimer <= uiDiff) + if (!uiIsMoving) // halt abilities in between phases { - if (bCheckChances()) - DoCast(me, SPELL_TRASH); - uiTrashTimer = urand(6000, 15500); - } else uiTrashTimer -= uiDiff; + if (uiTrashTimer <= uiDiff) + { + if (bCheckChances()) + DoCast(me, SPELL_TRASH); + uiTrashTimer = urand(6000, 15500); + } + else uiTrashTimer -= uiDiff; - if (uiSlamTimer <= uiDiff) - { - if (bCheckChances()) - DoCastVictim(SPELL_SMITE_SLAM); - uiSlamTimer = 11000; - } else uiSlamTimer -= uiDiff; + if (uiSlamTimer <= uiDiff) + { + if (bCheckChances()) + DoCastVictim(SPELL_SMITE_SLAM); + uiSlamTimer = 11000; + } + else uiSlamTimer -= uiDiff; - if (uiNimbleReflexesTimer <= uiDiff) - { - if (bCheckChances()) - DoCast(me, SPELL_NIMBLE_REFLEXES); - uiNimbleReflexesTimer = urand(27300, 60100); - } else uiNimbleReflexesTimer -= uiDiff; - /*END ACID-AI*/ + if (uiNimbleReflexesTimer <= uiDiff) + { + if (bCheckChances()) + DoCast(me, SPELL_NIMBLE_REFLEXES); + uiNimbleReflexesTimer = urand(27300, 60100); + } + else uiNimbleReflexesTimer -= uiDiff; + } if ((uiHealth == 0 && !HealthAbovePct(66)) || (uiHealth == 1 && !HealthAbovePct(33))) { ++uiHealth; DoCastAOE(SPELL_SMITE_STOMP, false); SetCombatMovement(false); - if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SMITE_CHEST))) + me->AttackStop(); + me->InterruptNonMeleeSpells(false); + me->SetReactState(REACT_PASSIVE); + uiTimer = 2500; + uiPhase = 1; + + switch (uiHealth) { - me->GetMotionMaster()->Clear(); - me->GetMotionMaster()->MovePoint(1, go->GetPositionX() - 3.0f, go->GetPositionY(), go->GetPositionZ()); + case 1: + Talk(SAY_PHASE_1); + break; + case 2: + Talk(SAY_PHASE_2); + break; } } @@ -147,21 +174,36 @@ public: switch (uiPhase) { case 1: - me->HandleEmoteCommand(EMOTE_STATE_KNEEL); //dosen't work? - uiTimer = 1000; - uiPhase = 2; + { + if (uiIsMoving) + break; + + if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SMITE_CHEST))) + { + me->GetMotionMaster()->Clear(); + me->GetMotionMaster()->MovePoint(1, go->GetPositionX() - 1.5f, go->GetPositionY() + 1.4f, go->GetPositionZ()); + uiIsMoving = true; + } break; + } case 2: if (uiHealth == 1) - SetEquipmentSlots(false, EQUIP_SWORD, EQUIP_SWORD, EQUIP_NO_CHANGE); + SetEquipmentSlots(false, EQUIP_AXE, EQUIP_AXE, EQUIP_NO_CHANGE); else SetEquipmentSlots(false, EQUIP_MACE, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); uiTimer = 500; uiPhase = 3; break; case 3: + me->SetStandState(UNIT_STAND_STATE_STAND); + uiTimer = 750; + uiPhase = 4; + break; + case 4: + me->SetReactState(REACT_AGGRESSIVE); SetCombatMovement(true); me->GetMotionMaster()->MoveChase(me->GetVictim(), me->m_CombatDistance); + uiIsMoving = false; uiPhase = 0; break; } @@ -176,8 +218,11 @@ public: if (uiType != POINT_MOTION_TYPE) return; - uiTimer = 1500; - uiPhase = 1; + me->SetFacingTo(5.47f); + me->SetStandState(UNIT_STAND_STATE_KNEEL); + + uiTimer = 2000; + uiPhase = 2; } }; }; diff --git a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h index dff4243617e..01ebabb160e 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h +++ b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h @@ -26,6 +26,7 @@ enum CannonState CANNON_GUNPOWDER_USED, CANNON_BLAST_INITIATED, PIRATES_ATTACK, + SMITE_ALARMED, EVENT_DONE }; @@ -48,4 +49,16 @@ enum GameObjects GO_DOOR_LEVER = 101833, GO_MR_SMITE_CHEST = 144111 }; + +enum CreaturesIds +{ + NPC_MR_SMITE = 646 +}; + +enum InstanceTexts +{ + SAY_ALARM1 = 0, + SAY_ALARM2 = 1 +}; + #endif diff --git a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp index 6714b243765..7599cf38f08 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp @@ -32,18 +32,14 @@ EndScriptData */ enum Sounds { SOUND_CANNONFIRE = 1400, - SOUND_DESTROYDOOR = 3079, - SOUND_MR_SMITE_ALARM1 = 5775, - SOUND_MR_SMITE_ALARM2 = 5777 + SOUND_DESTROYDOOR = 3079 }; -#define SAY_MR_SMITE_ALARM1 "You there, check out that noise!" -#define SAY_MR_SMITE_ALARM2 "We're under attack! A vast, ye swabs! Repel the invaders!" - enum Misc { DATA_CANNON_BLAST_TIMER = 3000, - DATA_PIRATES_DELAY_TIMER = 1000 + DATA_PIRATES_DELAY_TIMER = 1000, + DATA_SMITE_ALARM_DELAY_TIMER = 5000 }; class instance_deadmines : public InstanceMapScript @@ -63,6 +59,7 @@ class instance_deadmines : public InstanceMapScript State = CANNON_NOT_USED; CannonBlast_Timer = 0; PiratesDelay_Timer = 0; + SmiteAlarmDelay_Timer = 0; } ObjectGuid FactoryDoorGUID; @@ -72,10 +69,12 @@ class instance_deadmines : public InstanceMapScript ObjectGuid DefiasPirate1GUID; ObjectGuid DefiasPirate2GUID; ObjectGuid DefiasCompanionGUID; + ObjectGuid MrSmiteGUID; uint32 State; uint32 CannonBlast_Timer; uint32 PiratesDelay_Timer; + uint32 SmiteAlarmDelay_Timer; ObjectGuid uiSmiteChestGUID; virtual void Update(uint32 diff) override @@ -91,22 +90,20 @@ class instance_deadmines : public InstanceMapScript { case CANNON_GUNPOWDER_USED: CannonBlast_Timer = DATA_CANNON_BLAST_TIMER; - // it's a hack - Mr. Smite should do that but his too far away - //pIronCladDoor->SetName("Mr. Smite"); - //pIronCladDoor->MonsterYell(SAY_MR_SMITE_ALARM1, LANG_UNIVERSAL, NULL); - pIronCladDoor->PlayDirectSound(SOUND_MR_SMITE_ALARM1); State = CANNON_BLAST_INITIATED; break; case CANNON_BLAST_INITIATED: PiratesDelay_Timer = DATA_PIRATES_DELAY_TIMER; + SmiteAlarmDelay_Timer = DATA_SMITE_ALARM_DELAY_TIMER; if (CannonBlast_Timer <= diff) { SummonCreatures(); ShootCannon(); BlastOutDoor(); LeverStucked(); - //pIronCladDoor->MonsterYell(SAY_MR_SMITE_ALARM2, LANG_UNIVERSAL, NULL); - pIronCladDoor->PlayDirectSound(SOUND_MR_SMITE_ALARM2); + instance->LoadGrid(-22.8f, -797.24f); // Loads Mr. Smite's grid. + if (Creature* smite = instance->GetCreature(MrSmiteGUID)) // goes off when door blows up + smite->AI()->Talk(SAY_ALARM1); State = PIRATES_ATTACK; } else CannonBlast_Timer -= diff; break; @@ -114,9 +111,17 @@ class instance_deadmines : public InstanceMapScript if (PiratesDelay_Timer <= diff) { MoveCreaturesInside(); - State = EVENT_DONE; + State = SMITE_ALARMED; } else PiratesDelay_Timer -= diff; break; + case SMITE_ALARMED: + if (SmiteAlarmDelay_Timer <= diff) + { + if (Creature* smite = instance->GetCreature(MrSmiteGUID)) + smite->AI()->Talk(SAY_ALARM2); + State = EVENT_DONE; + } else SmiteAlarmDelay_Timer -= diff; + break; } } @@ -180,6 +185,18 @@ class instance_deadmines : public InstanceMapScript pDoorLever->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } + void OnCreatureCreate(Creature* creature) override + { + switch (creature->GetEntry()) + { + case NPC_MR_SMITE: + MrSmiteGUID = creature->GetGUID(); + break; + default: + break; + } + } + void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp index 05d964124b1..c8eb645845b 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp @@ -305,7 +305,7 @@ public: me->SummonCreature(NPC_CAVERNDEEP_AMBUSHER, SpawnPosition[9], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 2: - if (GameObject* go = me->SummonGameObject(183410, -533.140f, -105.322f, -156.016f, 0, 0, 0, 0, 0, 1)) + if (GameObject* go = me->SummonGameObject(183410, -533.140f, -105.322f, -156.016f, 0.f, G3D::Quat(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -320,7 +320,7 @@ public: Talk(SAY_BLASTMASTER_7); break; case 4: - if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0, 0, 0, 0, 0, 1)) + if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0.f, G3D::Quat(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); @@ -334,7 +334,7 @@ public: me->SummonCreature(NPC_CAVERNDEEP_AMBUSHER, SpawnPosition[14], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 6: - if (GameObject* go = me->SummonGameObject(183410, -507.820f, -103.333f, -151.353f, 0, 0, 0, 0, 0, 1)) + if (GameObject* go = me->SummonGameObject(183410, -507.820f, -103.333f, -151.353f, 0.f, G3D::Quat(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -342,7 +342,7 @@ public: } break; case 7: - if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0, 0, 0, 0, 0, 1)) + if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0.f, G3D::Quat(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -354,9 +354,9 @@ public: me->SummonCreature(NPC_CHOMPER, SpawnPosition[16], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 9: - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[17].GetPositionX(), SpawnPosition[17].GetPositionY(), SpawnPosition[17].GetPositionZ(), SpawnPosition[17].GetOrientation(), 0, 0, 0, 0, 7200); - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[18].GetPositionX(), SpawnPosition[18].GetPositionY(), SpawnPosition[18].GetPositionZ(), SpawnPosition[18].GetOrientation(), 0, 0, 0, 0, 7200); - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[19].GetPositionX(), SpawnPosition[19].GetPositionY(), SpawnPosition[19].GetPositionZ(), SpawnPosition[19].GetOrientation(), 0, 0, 0, 0, 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[17], G3D::Quat(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[18], G3D::Quat(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[19], G3D::Quat(), 7200); break; } } diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp index 9f4a31fdbbc..b694c074879 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp @@ -50,19 +50,9 @@ class boss_maiden_of_virtue : public CreatureScript public: boss_maiden_of_virtue() : CreatureScript("boss_maiden_of_virtue") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_maiden_of_virtueAI(creature); - } - struct boss_maiden_of_virtueAI : public BossAI { - boss_maiden_of_virtueAI(Creature* creature) : BossAI(creature, TYPE_MAIDEN) { } - - void Reset() override - { - _Reset(); - } + boss_maiden_of_virtueAI(Creature* creature) : BossAI(creature, DATA_MAIDEN_OF_VIRTUE) { } void KilledUnit(Unit* /*Victim*/) override { @@ -132,6 +122,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new boss_maiden_of_virtueAI(creature); + } }; void AddSC_boss_maiden_of_virtue() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp index ced8dd8f37e..ce3e68d9c48 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp @@ -26,26 +26,44 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellInfo.h" +#include "karazhan.h" -enum Midnight +enum Texts { - SAY_MIDNIGHT_KILL = 0, - SAY_APPEAR = 1, - SAY_MOUNT = 2, - - SAY_KILL = 0, - SAY_DISARMED = 1, - SAY_DEATH = 2, - SAY_RANDOM = 3, - - SPELL_SHADOWCLEAVE = 29832, - SPELL_INTANGIBLE_PRESENCE = 29833, - SPELL_BERSERKER_CHARGE = 26561, //Only when mounted + SAY_KILL = 0, + SAY_RANDOM = 1, + SAY_DISARMED = 2, + SAY_MIDNIGHT_KILL = 3, + SAY_APPEAR = 4, + SAY_MOUNT = 5, + + SAY_DEATH = 3, + + // Midnight + EMOTE_CALL_ATTUMEN = 0, + EMOTE_MOUNT_UP = 1 +}; - MOUNTED_DISPLAYID = 16040, +enum Spells +{ + // Attumen + SPELL_SHADOWCLEAVE = 29832, + SPELL_INTANGIBLE_PRESENCE = 29833, + SPELL_SPAWN_SMOKE = 10389, + SPELL_CHARGE = 29847, + + // Midnight + SPELL_KNOCKDOWN = 29711, + SPELL_SUMMON_ATTUMEN = 29714, + SPELL_MOUNT = 29770, + SPELL_SUMMON_ATTUMEN_MOUNTED = 29799 +}; - //Attumen (@todo Use the summoning spell instead of Creature id. It works, but is not convenient for us) - SUMMON_ATTUMEN = 15550, +enum Phases +{ + PHASE_NONE, + PHASE_ATTUMEN_ENGAGES, + PHASE_MOUNTED }; class boss_attumen : public CreatureScript @@ -53,72 +71,212 @@ class boss_attumen : public CreatureScript public: boss_attumen() : CreatureScript("boss_attumen") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_attumenAI(creature); - } - - struct boss_attumenAI : public ScriptedAI + struct boss_attumenAI : public BossAI { - boss_attumenAI(Creature* creature) : ScriptedAI(creature) + boss_attumenAI(Creature* creature) : BossAI(creature, DATA_ATTUMEN) { Initialize(); - - Phase = 1; - - CleaveTimer = urand(10000, 15000); - CurseTimer = 30000; - RandomYellTimer = urand(30000, 60000); //Occasionally yell - ChargeTimer = 20000; - } + } void Initialize() { - ResetTimer = 0; - Midnight.Clear(); + _midnightGUID.Clear(); + _phase = PHASE_NONE; } - ObjectGuid Midnight; - uint8 Phase; - uint32 CleaveTimer; - uint32 CurseTimer; - uint32 RandomYellTimer; - uint32 ChargeTimer; //only when mounted - uint32 ResetTimer; - void Reset() override { Initialize(); + BossAI::Reset(); + } + + void EnterEvadeMode(EvadeReason /*why*/) override + { + if (Creature* midnight = ObjectAccessor::GetCreature(*me, _midnightGUID)) + BossAI::_DespawnAtEvade(Seconds(10), midnight); + + me->DespawnOrUnsummon(); } - void EnterEvadeMode(EvadeReason why) override + void ScheduleTasks() override { - ScriptedAI::EnterEvadeMode(why); - ResetTimer = 2000; + scheduler.Schedule(Seconds(15), Seconds(25), [this](TaskContext task) + { + DoCastVictim(SPELL_SHADOWCLEAVE); + task.Repeat(Seconds(15), Seconds(25)); + }); + + scheduler.Schedule(Seconds(25), Seconds(45), [this](TaskContext task) + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) + DoCast(target,SPELL_INTANGIBLE_PRESENCE); + + task.Repeat(Seconds(25), Seconds(45)); + }); + + scheduler.Schedule(Seconds(30), Seconds(60), [this](TaskContext task) + { + Talk(SAY_RANDOM); + task.Repeat(Seconds(30), Seconds(60)); + }); } - void EnterCombat(Unit* /*who*/) override { } + void DamageTaken(Unit* /*attacker*/, uint32 &damage) override + { + // Attumen does not die until he mounts Midnight, let health fall to 1 and prevent further damage. + if (damage >= me->GetHealth() && _phase != PHASE_MOUNTED) + damage = me->GetHealth() - 1; + + if (_phase == PHASE_ATTUMEN_ENGAGES && me->HealthBelowPctDamaged(25, damage)) + { + _phase = PHASE_NONE; + + if (Creature* midnight = ObjectAccessor::GetCreature(*me, _midnightGUID)) + midnight->AI()->DoCastAOE(SPELL_MOUNT, true); + } + } void KilledUnit(Unit* /*victim*/) override { Talk(SAY_KILL); } - void JustDied(Unit* /*killer*/) override + void JustSummoned(Creature* summon) override + { + if (summon->GetEntry() == NPC_ATTUMEN_MOUNTED) + if (Creature* midnight = ObjectAccessor::GetCreature(*me, _midnightGUID)) + { + if (midnight->GetHealth() > me->GetHealth()) + summon->SetHealth(midnight->GetHealth()); + else + summon->SetHealth(me->GetHealth()); + + summon->AI()->DoZoneInCombat(); + summon->AI()->SetGUID(_midnightGUID, NPC_MIDNIGHT); + } + + BossAI::JustSummoned(summon); + } + + void IsSummonedBy(Unit* summoner) override + { + if (summoner->GetEntry() == NPC_MIDNIGHT) + _phase = PHASE_ATTUMEN_ENGAGES; + + if (summoner->GetEntry() == NPC_ATTUMEN_UNMOUNTED) + { + _phase = PHASE_MOUNTED; + DoCastSelf(SPELL_SPAWN_SMOKE); + + scheduler.Schedule(Seconds(10), Seconds(25), [this](TaskContext task) + { + Unit* target = nullptr; + ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + std::vector<Unit*> target_list; + + for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) + { + target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); + if (target && !target->IsWithinDist(me, 8.00f, false) && target->IsWithinDist(me, 25.0f, false)) + target_list.push_back(target); + + target = nullptr; + } + + if (!target_list.empty()) + target = Trinity::Containers::SelectRandomContainerElement(target_list); + + DoCast(target, SPELL_CHARGE); + task.Repeat(Seconds(10), Seconds(25)); + }); + + scheduler.Schedule(Seconds(25), Seconds(35), [this](TaskContext task) + { + DoCastVictim(SPELL_KNOCKDOWN); + task.Repeat(Seconds(25), Seconds(35)); + }); + } + } + + void JustDied(Unit* killer) override { Talk(SAY_DEATH); - if (Unit* midnight = ObjectAccessor::GetUnit(*me, Midnight)) + if (Unit* midnight = ObjectAccessor::GetUnit(*me, _midnightGUID)) midnight->KillSelf(); + + BossAI::JustDied(killer); } - void UpdateAI(uint32 diff) override; + void SetGUID(ObjectGuid guid, int32 data) override + { + if (data == NPC_MIDNIGHT) + _midnightGUID = guid; + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim() && _phase != PHASE_NONE) + return; + + scheduler.Update(diff, + std::bind(&BossAI::DoMeleeAttackIfReady, this)); + } void SpellHit(Unit* /*source*/, const SpellInfo* spell) override { if (spell->Mechanic == MECHANIC_DISARM) Talk(SAY_DISARMED); + + if (spell->Id == SPELL_MOUNT) + { + if (Creature* midnight = ObjectAccessor::GetCreature(*me, _midnightGUID)) + { + _phase = PHASE_NONE; + scheduler.CancelAll(); + + midnight->AttackStop(); + midnight->RemoveAllAttackers(); + midnight->SetReactState(REACT_PASSIVE); + midnight->GetMotionMaster()->MoveChase(me); + midnight->AI()->Talk(EMOTE_MOUNT_UP); + + me->AttackStop(); + me->RemoveAllAttackers(); + me->SetReactState(REACT_PASSIVE); + me->GetMotionMaster()->MoveChase(midnight); + Talk(SAY_MOUNT); + + scheduler.Schedule(Seconds(3), [this](TaskContext task) + { + if (Creature* midnight = ObjectAccessor::GetCreature(*me, _midnightGUID)) + { + if (me->IsWithinMeleeRange(midnight)) + { + DoCastAOE(SPELL_SUMMON_ATTUMEN_MOUNTED); + me->SetVisible(false); + midnight->SetVisible(false); + } + else + { + midnight->GetMotionMaster()->MoveChase(me); + me->GetMotionMaster()->MoveChase(midnight); + task.Repeat(Seconds(3)); + } + } + }); + } + } } + + private: + ObjectGuid _midnightGUID; + uint8 _phase; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new boss_attumenAI(creature); + } }; class boss_midnight : public CreatureScript @@ -126,210 +284,102 @@ class boss_midnight : public CreatureScript public: boss_midnight() : CreatureScript("boss_midnight") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_midnightAI(creature); - } - - struct boss_midnightAI : public ScriptedAI + struct boss_midnightAI : public BossAI { - boss_midnightAI(Creature* creature) : ScriptedAI(creature) + boss_midnightAI(Creature* creature) : BossAI(creature, DATA_ATTUMEN) { Initialize(); } void Initialize() { - Phase = 1; - Attumen.Clear(); - Mount_Timer = 0; + _phase = PHASE_NONE; } - ObjectGuid Attumen; - uint8 Phase; - uint32 Mount_Timer; - void Reset() override { Initialize(); - - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + BossAI::Reset(); me->SetVisible(true); + me->SetReactState(REACT_DEFENSIVE); } - void EnterCombat(Unit* /*who*/) override { } - - void KilledUnit(Unit* /*victim*/) override - { - if (Phase == 2) - { - if (Unit* unit = ObjectAccessor::GetUnit(*me, Attumen)) - Talk(SAY_MIDNIGHT_KILL, unit); - } - } - - void UpdateAI(uint32 diff) override + void DamageTaken(Unit* /*attacker*/, uint32 &damage) override { - if (!UpdateVictim()) - return; + // Midnight never dies, let health fall to 1 and prevent further damage. + if (damage >= me->GetHealth()) + damage = me->GetHealth() - 1; - if (Phase == 1 && HealthBelowPct(95)) + if (_phase == PHASE_NONE && me->HealthBelowPctDamaged(95, damage)) { - Phase = 2; - if (Creature* attumen = me->SummonCreature(SUMMON_ATTUMEN, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 30000)) - { - Attumen = attumen->GetGUID(); - attumen->AI()->AttackStart(me->GetVictim()); - SetMidnight(attumen, me->GetGUID()); - Talk(SAY_APPEAR, attumen); - } + _phase = PHASE_ATTUMEN_ENGAGES; + Talk(EMOTE_CALL_ATTUMEN); + DoCastAOE(SPELL_SUMMON_ATTUMEN); } - else if (Phase == 2 && HealthBelowPct(25)) + else if (_phase == PHASE_ATTUMEN_ENGAGES && me->HealthBelowPctDamaged(25, damage)) { - if (Unit* pAttumen = ObjectAccessor::GetUnit(*me, Attumen)) - Mount(pAttumen); + _phase = PHASE_MOUNTED; + DoCastAOE(SPELL_MOUNT, true); } - else if (Phase == 3) + } + + void JustSummoned(Creature* summon) override + { + if (summon->GetEntry() == NPC_ATTUMEN_UNMOUNTED) { - if (Mount_Timer) - { - if (Mount_Timer <= diff) - { - Mount_Timer = 0; - me->SetVisible(false); - me->GetMotionMaster()->MoveIdle(); - if (Unit* pAttumen = ObjectAccessor::GetUnit(*me, Attumen)) - { - pAttumen->SetDisplayId(MOUNTED_DISPLAYID); - pAttumen->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - if (pAttumen->GetVictim()) - { - pAttumen->GetMotionMaster()->MoveChase(pAttumen->GetVictim()); - pAttumen->SetTarget(pAttumen->EnsureVictim()->GetGUID()); - } - pAttumen->SetObjectScale(1); - } - } else Mount_Timer -= diff; - } + _attumenGUID = summon->GetGUID(); + summon->AI()->SetGUID(me->GetGUID(), NPC_MIDNIGHT); + summon->AI()->AttackStart(me->GetVictim()); + summon->AI()->Talk(SAY_APPEAR); } - if (Phase != 3) - DoMeleeAttackIfReady(); + BossAI::JustSummoned(summon); } - void Mount(Unit* pAttumen) + void EnterCombat(Unit* who) override { - Talk(SAY_MOUNT, pAttumen); - Phase = 3; - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - pAttumen->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - float angle = me->GetAngle(pAttumen); - float distance = me->GetDistance2d(pAttumen); - float newX = me->GetPositionX() + std::cos(angle)*(distance/2); - float newY = me->GetPositionY() + std::sin(angle)*(distance/2); - float newZ = 50; - //me->Relocate(newX, newY, newZ, angle); - //me->SendMonsterMove(newX, newY, newZ, 0, true, 1000); - me->GetMotionMaster()->Clear(); - me->GetMotionMaster()->MovePoint(0, newX, newY, newZ); - distance += 10; - newX = me->GetPositionX() + std::cos(angle)*(distance/2); - newY = me->GetPositionY() + std::sin(angle)*(distance/2); - pAttumen->GetMotionMaster()->Clear(); - pAttumen->GetMotionMaster()->MovePoint(0, newX, newY, newZ); - //pAttumen->Relocate(newX, newY, newZ, -angle); - //pAttumen->SendMonsterMove(newX, newY, newZ, 0, true, 1000); - Mount_Timer = 1000; + BossAI::EnterCombat(who); + + scheduler.Schedule(Seconds(15), Seconds(25), [this](TaskContext task) + { + DoCastVictim(SPELL_KNOCKDOWN); + task.Repeat(Seconds(15), Seconds(25)); + }); } - void SetMidnight(Creature* pAttumen, ObjectGuid value) + void EnterEvadeMode(EvadeReason /*why*/) override { - ENSURE_AI(boss_attumen::boss_attumenAI, pAttumen->AI())->Midnight = value; + BossAI::_DespawnAtEvade(Seconds(10)); } - }; -}; -void boss_attumen::boss_attumenAI::UpdateAI(uint32 diff) -{ - if (ResetTimer) - { - if (ResetTimer <= diff) + void KilledUnit(Unit* /*victim*/) override { - ResetTimer = 0; - Unit* pMidnight = ObjectAccessor::GetUnit(*me, Midnight); - if (pMidnight) + if (_phase == PHASE_ATTUMEN_ENGAGES) { - pMidnight->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - pMidnight->SetVisible(true); + if (Unit* unit = ObjectAccessor::GetUnit(*me, _attumenGUID)) + Talk(SAY_MIDNIGHT_KILL, unit); } - Midnight.Clear(); - me->SetVisible(false); - me->KillSelf(); - } else ResetTimer -= diff; - } - - //Return since we have no target - if (!UpdateVictim()) - return; - - if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) - return; - - if (CleaveTimer <= diff) - { - DoCastVictim(SPELL_SHADOWCLEAVE); - CleaveTimer = urand(10000, 15000); - } else CleaveTimer -= diff; + } - if (CurseTimer <= diff) - { - DoCastVictim(SPELL_INTANGIBLE_PRESENCE); - CurseTimer = 30000; - } else CurseTimer -= diff; + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim() || _phase == PHASE_MOUNTED) + return; - if (RandomYellTimer <= diff) - { - Talk(SAY_RANDOM); - RandomYellTimer = urand(30000, 60000); - } else RandomYellTimer -= diff; + scheduler.Update(diff, + std::bind(&BossAI::DoMeleeAttackIfReady, this)); + } - if (me->GetUInt32Value(UNIT_FIELD_DISPLAYID) == MOUNTED_DISPLAYID) - { - if (ChargeTimer <= diff) - { - Unit* target = NULL; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); - std::vector<Unit*> target_list; - for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) - { - target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); - if (target && !target->IsWithinDist(me, ATTACK_DISTANCE, false)) - target_list.push_back(target); - target = NULL; - } - if (!target_list.empty()) - target = *(target_list.begin() + rand32() % target_list.size()); + private: + ObjectGuid _attumenGUID; + uint8 _phase; + }; - DoCast(target, SPELL_BERSERKER_CHARGE); - ChargeTimer = 20000; - } else ChargeTimer -= diff; - } - else + CreatureAI* GetAI(Creature* creature) const override { - if (HealthBelowPct(25)) - { - Creature* pMidnight = ObjectAccessor::GetCreature(*me, Midnight); - if (pMidnight && pMidnight->GetTypeId() == TYPEID_UNIT) - { - ENSURE_AI(boss_midnight::boss_midnightAI, (pMidnight->AI()))->Mount(me); - me->SetHealth(pMidnight->GetHealth()); - DoResetThreat(); - } - } + return new boss_midnightAI(creature); } - - DoMeleeAttackIfReady(); -} +}; void AddSC_boss_attumen() { diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp index 79e36442f4b..29c78d3b388 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp @@ -143,12 +143,12 @@ public: if (me->IsAlive()) SpawnAdds(); - instance->SetData(TYPE_MOROES, NOT_STARTED); + instance->SetBossState(DATA_MOROES, NOT_STARTED); } void StartEvent() { - instance->SetData(TYPE_MOROES, IN_PROGRESS); + instance->SetBossState(DATA_MOROES, IN_PROGRESS); DoZoneInCombat(); } @@ -171,7 +171,7 @@ public: { Talk(SAY_DEATH); - instance->SetData(TYPE_MOROES, DONE); + instance->SetBossState(DATA_MOROES, DONE); DeSpawnAdds(); @@ -257,12 +257,6 @@ public: if (!UpdateVictim()) return; - if (!instance->GetData(TYPE_MOROES)) - { - EnterEvadeMode(); - return; - } - if (!Enrage && HealthBelowPct(30)) { DoCast(me, SPELL_FRENZY); @@ -304,7 +298,7 @@ public: if (Blind_Timer <= diff) { std::list<Unit*> targets; - SelectTargetList(targets, 5, SELECT_TARGET_RANDOM, me->GetMeleeReach()*5, true); + SelectTargetList(targets, 5, SELECT_TARGET_RANDOM, me->GetCombatReach()*5, true); for (std::list<Unit*>::const_iterator i = targets.begin(); i != targets.end(); ++i) if (!me->IsWithinMeleeRange(*i)) { @@ -347,7 +341,7 @@ struct boss_moroes_guestAI : public ScriptedAI void Reset() override { - instance->SetData(TYPE_MOROES, NOT_STARTED); + instance->SetBossState(DATA_MOROES, NOT_STARTED); } void AcquireGUID() @@ -373,7 +367,7 @@ struct boss_moroes_guestAI : public ScriptedAI void UpdateAI(uint32 /*diff*/) override { - if (!instance->GetData(TYPE_MOROES)) + if (instance->GetBossState(DATA_MOROES) != IN_PROGRESS) EnterEvadeMode(); DoMeleeAttackIfReady(); diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp index 6f5f2b8f65f..6ff20e66f7f 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp @@ -138,15 +138,15 @@ public: { Initialize(); - me->SetSpeed(MOVE_RUN, 2.0f); + me->SetSpeedRate(MOVE_RUN, 2.0f); me->SetDisableGravity(true); me->SetWalk(false); me->setActive(true); - if (instance->GetData(TYPE_NIGHTBANE) == DONE || instance->GetData(TYPE_NIGHTBANE) == IN_PROGRESS) + if (instance->GetBossState(DATA_NIGHTBANE) == DONE || instance->GetBossState(DATA_NIGHTBANE) == IN_PROGRESS) me->DisappearAndDie(); else - instance->SetData(TYPE_NIGHTBANE, NOT_STARTED); + instance->SetBossState(DATA_NIGHTBANE, NOT_STARTED); HandleTerraceDoors(true); @@ -165,10 +165,10 @@ public: void EnterCombat(Unit* /*who*/) override { - instance->SetData(TYPE_NIGHTBANE, IN_PROGRESS); + instance->SetBossState(DATA_NIGHTBANE, IN_PROGRESS); HandleTerraceDoors(false); - Talk(YELL_AGGRO); + Talk(YELL_AGGRO); } void AttackStart(Unit* who) override @@ -179,7 +179,7 @@ public: void JustDied(Unit* /*killer*/) override { - instance->SetData(TYPE_NIGHTBANE, DONE); + instance->SetBossState(DATA_NIGHTBANE, DONE); HandleTerraceDoors(true); } diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp index 450678a0f86..17a23a0b2e7 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp @@ -154,7 +154,7 @@ public: Initialize(); // Not in progress - instance->SetData(TYPE_ARAN, NOT_STARTED); + instance->SetBossState(DATA_ARAN, NOT_STARTED); instance->HandleGameObject(instance->GetGuidData(DATA_GO_LIBRARY_DOOR), true); } @@ -167,7 +167,7 @@ public: { Talk(SAY_DEATH); - instance->SetData(TYPE_ARAN, DONE); + instance->SetBossState(DATA_ARAN, DONE); instance->HandleGameObject(instance->GetGuidData(DATA_GO_LIBRARY_DOOR), true); } @@ -175,7 +175,7 @@ public: { Talk(SAY_AGGRO); - instance->SetData(TYPE_ARAN, IN_PROGRESS); + instance->SetBossState(DATA_ARAN, IN_PROGRESS); instance->HandleGameObject(instance->GetGuidData(DATA_GO_LIBRARY_DOOR), false); } diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp index 7bc835dcced..2e33f0933e3 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp @@ -61,7 +61,6 @@ enum Creatures NPC_DEMONCHAINS = 17248, NPC_FIENDISHIMP = 17267, NPC_PORTAL = 17265, - NPC_KILREK = 17229 }; @@ -316,7 +315,7 @@ public: Initialize(); - instance->SetData(TYPE_TERESTIAN, NOT_STARTED); + instance->SetBossState(DATA_TERESTIAN, NOT_STARTED); me->RemoveAurasDueToSpell(SPELL_BROKEN_PACT); @@ -371,7 +370,7 @@ public: Talk(SAY_DEATH); - instance->SetData(TYPE_TERESTIAN, DONE); + instance->SetBossState(DATA_TERESTIAN, DONE); } void UpdateAI(uint32 diff) override diff --git a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp index d4d0e6fa70d..2e4ac11d3fa 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp @@ -674,6 +674,12 @@ public: void Initialize() { + // Hello, developer from the future! It's me again! + // This time, you're fixing Karazhan scripts. Awesome. These are a mess of hacks. An amalgamation of hacks, so to speak. Maybe even a Patchwerk thereof. + // Anyway, I digress. + // @todo This line below is obviously a hack. Duh. I'm just coming in here to hackfix the encounter to actually be completable. + // It needs a rewrite. Badly. Please, take good care of it. + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NON_ATTACKABLE); CycloneTimer = 30000; ChainLightningTimer = 10000; } @@ -701,20 +707,12 @@ public: void EnterCombat(Unit* /*who*/) override { Talk(SAY_CRONE_AGGRO); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); } void JustDied(Unit* /*killer*/) override { Talk(SAY_CRONE_DEATH); - - instance->SetData(TYPE_OPERA, DONE); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORLEFT), true); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORRIGHT), true); - - if (GameObject* pSideEntrance = instance->instance->GetGameObject(instance->GetGuidData(DATA_GO_SIDE_ENTRANCE_DOOR))) - pSideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + instance->SetBossState(DATA_OPERA_PERFORMANCE, DONE); } void UpdateAI(uint32 diff) override @@ -722,9 +720,6 @@ public: if (!UpdateVictim()) return; - if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - if (CycloneTimer <= diff) { if (Creature* Cyclone = DoSpawnCreature(CREATURE_CYCLONE, float(urand(0, 9)), float(urand(0, 9)), 0, 0, TEMPSUMMON_TIMED_DESPAWN, 15000)) @@ -802,46 +797,43 @@ enum RedRidingHood SAY_WOLF_AGGRO = 0, SAY_WOLF_SLAY = 1, SAY_WOLF_HOOD = 2, + OPTION_WHAT_PHAT_LEWTS_YOU_HAVE = 7443, SOUND_WOLF_DEATH = 9275, SPELL_LITTLE_RED_RIDING_HOOD = 30768, SPELL_TERRIFYING_HOWL = 30752, SPELL_WIDE_SWIPE = 30761, - CREATURE_BIG_BAD_WOLF = 17521, + CREATURE_BIG_BAD_WOLF = 17521 }; - -#define GOSSIP_GRANDMA "What phat lewtz you have grandmother?" - - - class npc_grandmother : public CreatureScript { -public: - npc_grandmother() : CreatureScript("npc_grandmother") { } + public: + npc_grandmother() : CreatureScript("npc_grandmother") { } - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF) + struct npc_grandmotherAI : public ScriptedAI { - if (Creature* pBigBadWolf = creature->SummonCreature(CREATURE_BIG_BAD_WOLF, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, HOUR*2*IN_MILLISECONDS)) - pBigBadWolf->AI()->AttackStart(player); + npc_grandmotherAI(Creature* creature) : ScriptedAI(creature) { } - creature->DespawnOrUnsummon(); - } + void sGossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override + { + if (menuId == OPTION_WHAT_PHAT_LEWTS_YOU_HAVE && gossipListId == 0) + { + player->CLOSE_GOSSIP_MENU(); - return true; - } + if (Creature* pBigBadWolf = me->SummonCreature(CREATURE_BIG_BAD_WOLF, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, HOUR*2*IN_MILLISECONDS)) + pBigBadWolf->AI()->AttackStart(player); - bool OnGossipHello(Player* player, Creature* creature) override - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_GRANDMA, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(8990, creature->GetGUID()); + me->DespawnOrUnsummon(); + } + } + }; - return true; - } + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_grandmotherAI(creature); + } }; class boss_bigbadwolf : public CreatureScript @@ -908,13 +900,7 @@ public: void JustDied(Unit* /*killer*/) override { DoPlaySoundToSet(me, SOUND_WOLF_DEATH); - - instance->SetData(TYPE_OPERA, DONE); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORLEFT), true); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORRIGHT), true); - - if (GameObject* pSideEntrance = instance->instance->GetGameObject(instance->GetGuidData(DATA_GO_SIDE_ENTRANCE_DOOR))) - pSideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + instance->SetBossState(DATA_OPERA_PERFORMANCE, DONE); } void UpdateAI(uint32 diff) override @@ -1158,12 +1144,7 @@ public: void JustDied(Unit* /*killer*/) override { Talk(SAY_JULIANNE_DEATH02); - - instance->SetData(TYPE_OPERA, DONE); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORLEFT), true); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORRIGHT), true); - if (GameObject* pSideEntrance = instance->instance->GetGameObject(instance->GetGuidData(DATA_GO_SIDE_ENTRANCE_DOOR))) - pSideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + instance->SetBossState(DATA_OPERA_PERFORMANCE, DONE); } void KilledUnit(Unit* /*victim*/) override @@ -1316,13 +1297,7 @@ public: void JustDied(Unit* /*killer*/) override { Talk(SAY_ROMULO_DEATH); - - instance->SetData(TYPE_OPERA, DONE); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORLEFT), true); - instance->HandleGameObject(instance->GetGuidData(DATA_GO_STAGEDOORRIGHT), true); - - if (GameObject* pSideEntrance = instance->instance->GetGameObject(instance->GetGuidData(DATA_GO_SIDE_ENTRANCE_DOOR))) - pSideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + instance->SetBossState(DATA_OPERA_PERFORMANCE, DONE); } void KilledUnit(Unit* /*victim*/) override diff --git a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp index b725f421c8f..ad403e6aeed 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp @@ -27,8 +27,6 @@ EndScriptData */ #include "InstanceScript.h" #include "karazhan.h" -#define MAX_ENCOUNTER 12 - /* 0 - Attumen + Midnight (optional) 1 - Moroes @@ -47,8 +45,8 @@ EndScriptData */ const Position OptionalSpawn[] = { { -10960.981445f, -1940.138428f, 46.178097f, 4.12f }, // Hyakiss the Lurker - { -10899.903320f, -2085.573730f, 49.474449f, 1.38f }, // Rokad the Ravager - { -10945.769531f, -2040.153320f, 49.474438f, 0.077f } // Shadikith the Glider + { -10945.769531f, -2040.153320f, 49.474438f, 0.077f }, // Shadikith the Glider + { -10899.903320f, -2085.573730f, 49.474449f, 1.38f } // Rokad the Ravager }; class instance_karazhan : public InstanceMapScript @@ -66,53 +64,27 @@ public: instance_karazhan_InstanceMapScript(Map* map) : InstanceScript(map) { SetHeaders(DataHeader); - memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); + SetBossNumber(EncounterCount); // 1 - OZ, 2 - HOOD, 3 - RAJ, this never gets altered. - m_uiOperaEvent = urand(1, 3); - m_uiOzDeathCount = 0; + OperaEvent = urand(EVENT_OZ, EVENT_RAJ); + OzDeathCount = 0; OptionalBossCount = 0; } - uint32 m_auiEncounter[MAX_ENCOUNTER]; - std::string strSaveData; - - uint32 m_uiOperaEvent; - uint32 m_uiOzDeathCount; - uint32 OptionalBossCount; - - ObjectGuid m_uiCurtainGUID; - ObjectGuid m_uiStageDoorLeftGUID; - ObjectGuid m_uiStageDoorRightGUID; - ObjectGuid m_uiKilrekGUID; - ObjectGuid m_uiTerestianGUID; - ObjectGuid m_uiMoroesGUID; - ObjectGuid m_uiLibraryDoor; // Door at Shade of Aran - ObjectGuid m_uiMassiveDoor; // Door at Netherspite - ObjectGuid m_uiSideEntranceDoor; // Side Entrance - ObjectGuid m_uiGamesmansDoor; // Door before Chess - ObjectGuid m_uiGamesmansExitDoor; // Door after Chess - ObjectGuid m_uiNetherspaceDoor; // Door at Malchezaar - ObjectGuid MastersTerraceDoor[2]; - ObjectGuid ImageGUID; - ObjectGuid DustCoveredChest; - - bool IsEncounterInProgress() const override - { - for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) - if (m_auiEncounter[i] == IN_PROGRESS) - return true; - - return false; - } - void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { - case 17229: m_uiKilrekGUID = creature->GetGUID(); break; - case 15688: m_uiTerestianGUID = creature->GetGUID(); break; - case 15687: m_uiMoroesGUID = creature->GetGUID(); break; + case NPC_KILREK: + KilrekGUID = creature->GetGUID(); + break; + case NPC_TERESTIAN_ILLHOOF: + TerestianGUID = creature->GetGUID(); + break; + case NPC_MOROES: + MoroesGUID = creature->GetGUID(); + break; } } @@ -132,130 +104,129 @@ public: case NPC_PHASE_HOUND: case NPC_DREADBEAST: case NPC_SHADOWBEAST: - SetData(TYPE_OPTIONAL_BOSS, NOT_STARTED); - break; - default: - break; - } - } - - void SetData(uint32 type, uint32 uiData) override - { - switch (type) - { - case TYPE_ATTUMEN: m_auiEncounter[0] = uiData; break; - case TYPE_MOROES: - if (m_auiEncounter[1] == DONE) - break; - m_auiEncounter[1] = uiData; - break; - case TYPE_MAIDEN: m_auiEncounter[2] = uiData; break; - case TYPE_OPTIONAL_BOSS: - m_auiEncounter[3] = uiData; - if (uiData == NOT_STARTED) + if (GetBossState(DATA_OPTIONAL_BOSS) == TO_BE_DECIDED) { ++OptionalBossCount; - if (OptionalBossCount == 50) + if (OptionalBossCount == OPTIONAL_BOSS_REQUIRED_DEATH_COUNT) { - switch (urand(0, 2)) + switch (urand(NPC_HYAKISS_THE_LURKER, NPC_ROKAD_THE_RAVAGER)) { - case 0: + case NPC_HYAKISS_THE_LURKER: instance->SummonCreature(NPC_HYAKISS_THE_LURKER, OptionalSpawn[0]); break; - case 1: - instance->SummonCreature(NPC_ROKAD_THE_RAVAGER, OptionalSpawn[1]); + case NPC_SHADIKITH_THE_GLIDER: + instance->SummonCreature(NPC_SHADIKITH_THE_GLIDER, OptionalSpawn[1]); break; - case 2: - instance->SummonCreature(NPC_SHADIKITH_THE_GLIDER, OptionalSpawn[2]); + case NPC_ROKAD_THE_RAVAGER: + instance->SummonCreature(NPC_ROKAD_THE_RAVAGER, OptionalSpawn[2]); break; } } } break; - case TYPE_OPERA: - m_auiEncounter[4] = uiData; - if (uiData == DONE) - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, 16812, NULL); - break; - case TYPE_CURATOR: m_auiEncounter[5] = uiData; break; - case TYPE_ARAN: m_auiEncounter[6] = uiData; break; - case TYPE_TERESTIAN: m_auiEncounter[7] = uiData; break; - case TYPE_NETHERSPITE: m_auiEncounter[8] = uiData; break; - case TYPE_CHESS: - if (uiData == DONE) - DoRespawnGameObject(DustCoveredChest, DAY); - m_auiEncounter[9] = uiData; - break; - case TYPE_MALCHEZZAR: m_auiEncounter[10] = uiData; break; - case TYPE_NIGHTBANE: - if (m_auiEncounter[11] != DONE) - m_auiEncounter[11] = uiData; - break; - case DATA_OPERA_OZ_DEATHCOUNT: - if (uiData == SPECIAL) - ++m_uiOzDeathCount; - else if (uiData == IN_PROGRESS) - m_uiOzDeathCount = 0; + default: break; } + } - if (uiData == DONE) + void SetData(uint32 type, uint32 data) override + { + switch (type) { - OUT_SAVE_INST_DATA; - - std::ostringstream saveStream; - saveStream << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2] << ' ' - << m_auiEncounter[3] << ' ' << m_auiEncounter[4] << ' ' << m_auiEncounter[5] << ' ' << m_auiEncounter[6] << ' ' - << m_auiEncounter[7] << ' ' << m_auiEncounter[8] << ' ' << m_auiEncounter[9] << ' ' << m_auiEncounter[10] << ' ' << m_auiEncounter[11]; + case DATA_OPERA_OZ_DEATHCOUNT: + if (data == SPECIAL) + ++OzDeathCount; + else if (data == IN_PROGRESS) + OzDeathCount = 0; + break; + } + } - strSaveData = saveStream.str(); + bool SetBossState(uint32 type, EncounterState state) override + { + if (!InstanceScript::SetBossState(type, state)) + return false; - SaveToDB(); - OUT_SAVE_INST_DATA_COMPLETE; + switch (type) + { + case DATA_OPERA_PERFORMANCE: + if (state == DONE) + { + HandleGameObject(StageDoorLeftGUID, true); + HandleGameObject(StageDoorRightGUID, true); + if (GameObject* sideEntrance = instance->GetGameObject(SideEntranceDoor)) + sideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, 16812, NULL); + } + break; + case DATA_CHESS: + if (state == DONE) + DoRespawnGameObject(DustCoveredChest, DAY); + break; + default: + break; } + + return true; } - void SetGuidData(uint32 identifier, ObjectGuid data) override + void SetGuidData(uint32 type, ObjectGuid data) override { - switch (identifier) - { - case DATA_IMAGE_OF_MEDIVH: ImageGUID = data; - } + if (type == DATA_IMAGE_OF_MEDIVH) + ImageGUID = data; } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { - case 183932: m_uiCurtainGUID = go->GetGUID(); break; - case 184278: - m_uiStageDoorLeftGUID = go->GetGUID(); - if (m_auiEncounter[4] == DONE) + case GO_STAGE_CURTAIN: + CurtainGUID = go->GetGUID(); + break; + case GO_STAGE_DOOR_LEFT: + StageDoorLeftGUID = go->GetGUID(); + if (GetBossState(DATA_OPERA_PERFORMANCE) == DONE) go->SetGoState(GO_STATE_ACTIVE); break; - case 184279: - m_uiStageDoorRightGUID = go->GetGUID(); - if (m_auiEncounter[4] == DONE) + case GO_STAGE_DOOR_RIGHT: + StageDoorRightGUID = go->GetGUID(); + if (GetBossState(DATA_OPERA_PERFORMANCE) == DONE) go->SetGoState(GO_STATE_ACTIVE); break; - case 184517: m_uiLibraryDoor = go->GetGUID(); break; - case 185521: m_uiMassiveDoor = go->GetGUID(); break; - case 184276: m_uiGamesmansDoor = go->GetGUID(); break; - case 184277: m_uiGamesmansExitDoor = go->GetGUID(); break; - case 185134: m_uiNetherspaceDoor = go->GetGUID(); break; - case 184274: MastersTerraceDoor[0] = go->GetGUID(); break; - case 184280: MastersTerraceDoor[1] = go->GetGUID(); break; - case 184275: - m_uiSideEntranceDoor = go->GetGUID(); - if (m_auiEncounter[4] == DONE) + case GO_PRIVATE_LIBRARY_DOOR: + LibraryDoor = go->GetGUID(); + break; + case GO_MASSIVE_DOOR: + MassiveDoor = go->GetGUID(); + break; + case GO_GAMESMAN_HALL_DOOR: + GamesmansDoor = go->GetGUID(); + break; + case GO_GAMESMAN_HALL_EXIT_DOOR: + GamesmansExitDoor = go->GetGUID(); + break; + case GO_NETHERSPACE_DOOR: + NetherspaceDoor = go->GetGUID(); + break; + case GO_MASTERS_TERRACE_DOOR: + MastersTerraceDoor[0] = go->GetGUID(); + break; + case GO_MASTERS_TERRACE_DOOR2: + MastersTerraceDoor[1] = go->GetGUID(); + break; + case GO_SIDE_ENTRANCE_DOOR: + SideEntranceDoor = go->GetGUID(); + if (GetBossState(DATA_OPERA_PERFORMANCE) == DONE) go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); else go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); break; - case 185119: DustCoveredChest = go->GetGUID(); break; + case GO_DUST_COVERED_CHEST: + DustCoveredChest = go->GetGUID(); + break; } - switch (m_uiOperaEvent) + switch (OperaEvent) { /// @todo Set Object visibilities for Opera based on performance case EVENT_OZ: @@ -269,77 +240,77 @@ public: } } - std::string GetSaveData() override - { - return strSaveData; - } - - uint32 GetData(uint32 uiData) const override + uint32 GetData(uint32 type) const override { - switch (uiData) + switch (type) { - case TYPE_ATTUMEN: return m_auiEncounter[0]; - case TYPE_MOROES: return m_auiEncounter[1]; - case TYPE_MAIDEN: return m_auiEncounter[2]; - case TYPE_OPTIONAL_BOSS: return m_auiEncounter[3]; - case TYPE_OPERA: return m_auiEncounter[4]; - case TYPE_CURATOR: return m_auiEncounter[5]; - case TYPE_ARAN: return m_auiEncounter[6]; - case TYPE_TERESTIAN: return m_auiEncounter[7]; - case TYPE_NETHERSPITE: return m_auiEncounter[8]; - case TYPE_CHESS: return m_auiEncounter[9]; - case TYPE_MALCHEZZAR: return m_auiEncounter[10]; - case TYPE_NIGHTBANE: return m_auiEncounter[11]; - case DATA_OPERA_PERFORMANCE: return m_uiOperaEvent; - case DATA_OPERA_OZ_DEATHCOUNT: return m_uiOzDeathCount; + case DATA_OPERA_PERFORMANCE: + return OperaEvent; + case DATA_OPERA_OZ_DEATHCOUNT: + return OzDeathCount; } return 0; } - ObjectGuid GetGuidData(uint32 uiData) const override + ObjectGuid GetGuidData(uint32 type) const override { - switch (uiData) + switch (type) { - case DATA_KILREK: return m_uiKilrekGUID; - case DATA_TERESTIAN: return m_uiTerestianGUID; - case DATA_MOROES: return m_uiMoroesGUID; - case DATA_GO_STAGEDOORLEFT: return m_uiStageDoorLeftGUID; - case DATA_GO_STAGEDOORRIGHT: return m_uiStageDoorRightGUID; - case DATA_GO_CURTAINS: return m_uiCurtainGUID; - case DATA_GO_LIBRARY_DOOR: return m_uiLibraryDoor; - case DATA_GO_MASSIVE_DOOR: return m_uiMassiveDoor; - case DATA_GO_SIDE_ENTRANCE_DOOR: return m_uiSideEntranceDoor; - case DATA_GO_GAME_DOOR: return m_uiGamesmansDoor; - case DATA_GO_GAME_EXIT_DOOR: return m_uiGamesmansExitDoor; - case DATA_GO_NETHER_DOOR: return m_uiNetherspaceDoor; - case DATA_MASTERS_TERRACE_DOOR_1: return MastersTerraceDoor[0]; - case DATA_MASTERS_TERRACE_DOOR_2: return MastersTerraceDoor[1]; - case DATA_IMAGE_OF_MEDIVH: return ImageGUID; + case DATA_KILREK: + return KilrekGUID; + case DATA_TERESTIAN: + return TerestianGUID; + case DATA_MOROES: + return MoroesGUID; + case DATA_GO_STAGEDOORLEFT: + return StageDoorLeftGUID; + case DATA_GO_STAGEDOORRIGHT: + return StageDoorRightGUID; + case DATA_GO_CURTAINS: + return CurtainGUID; + case DATA_GO_LIBRARY_DOOR: + return LibraryDoor; + case DATA_GO_MASSIVE_DOOR: + return MassiveDoor; + case DATA_GO_SIDE_ENTRANCE_DOOR: + return SideEntranceDoor; + case DATA_GO_GAME_DOOR: + return GamesmansDoor; + case DATA_GO_GAME_EXIT_DOOR: + return GamesmansExitDoor; + case DATA_GO_NETHER_DOOR: + return NetherspaceDoor; + case DATA_MASTERS_TERRACE_DOOR_1: + return MastersTerraceDoor[0]; + case DATA_MASTERS_TERRACE_DOOR_2: + return MastersTerraceDoor[1]; + case DATA_IMAGE_OF_MEDIVH: + return ImageGUID; } return ObjectGuid::Empty; } - void Load(char const* chrIn) override - { - if (!chrIn) - { - OUT_LOAD_INST_DATA_FAIL; - return; - } - - OUT_LOAD_INST_DATA(chrIn); - std::istringstream loadStream(chrIn); - - loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] - >> m_auiEncounter[4] >> m_auiEncounter[5] >> m_auiEncounter[6] >> m_auiEncounter[7] - >> m_auiEncounter[8] >> m_auiEncounter[9] >> m_auiEncounter[10] >> m_auiEncounter[11]; - for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) - if (m_auiEncounter[i] == IN_PROGRESS) // Do not load an encounter as "In Progress" - reset it instead. - m_auiEncounter[i] = NOT_STARTED; - OUT_LOAD_INST_DATA_COMPLETE; - } + private: + uint32 OperaEvent; + uint32 OzDeathCount; + uint32 OptionalBossCount; + ObjectGuid CurtainGUID; + ObjectGuid StageDoorLeftGUID; + ObjectGuid StageDoorRightGUID; + ObjectGuid KilrekGUID; + ObjectGuid TerestianGUID; + ObjectGuid MoroesGUID; + ObjectGuid LibraryDoor; // Door at Shade of Aran + ObjectGuid MassiveDoor; // Door at Netherspite + ObjectGuid SideEntranceDoor; // Side Entrance + ObjectGuid GamesmansDoor; // Door before Chess + ObjectGuid GamesmansExitDoor; // Door after Chess + ObjectGuid NetherspaceDoor; // Door at Malchezaar + ObjectGuid MastersTerraceDoor[2]; + ObjectGuid ImageGUID; + ObjectGuid DustCoveredChest; }; }; diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp index aa2da8cc391..ace15cc2a7e 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp @@ -168,7 +168,7 @@ public: void StartEvent() { - instance->SetData(TYPE_OPERA, IN_PROGRESS); + instance->SetBossState(DATA_OPERA_PERFORMANCE, IN_PROGRESS); //resets count for this event, in case earlier failed if (m_uiEventId == EVENT_OZ) @@ -377,7 +377,7 @@ public: if (InstanceScript* instance = creature->GetInstanceScript()) { // Check for death of Moroes and if opera event is not done already - if (instance->GetData(TYPE_MOROES) == DONE && instance->GetData(TYPE_OPERA) != DONE) + if (instance->GetBossState(DATA_MOROES) == DONE && instance->GetBossState(DATA_OPERA_PERFORMANCE) != DONE) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, OZ_GOSSIP1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); @@ -562,7 +562,7 @@ public: arca->GetMotionMaster()->MovePoint(0, -11010.82f, -1761.18f, 156.47f); arca->setActive(true); arca->InterruptNonMeleeSpells(true); - arca->SetSpeed(MOVE_FLIGHT, 2.0f); + arca->SetSpeedRate(MOVE_FLIGHT, 2.0f); } return 10000; case 13: diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h index 4d86492257c..2dc3750dc5b 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h @@ -21,27 +21,26 @@ #define DataHeader "KZ" +uint32 const EncounterCount = 12; + enum DataTypes { - TYPE_ATTUMEN = 1, - TYPE_MOROES = 2, - TYPE_MAIDEN = 3, - TYPE_OPTIONAL_BOSS = 4, - TYPE_OPERA = 5, - TYPE_CURATOR = 6, - TYPE_ARAN = 7, - TYPE_TERESTIAN = 8, - TYPE_NETHERSPITE = 9, - TYPE_CHESS = 10, - TYPE_MALCHEZZAR = 11, - TYPE_NIGHTBANE = 12, + DATA_ATTUMEN = 0, + DATA_MOROES = 1, + DATA_MAIDEN_OF_VIRTUE = 2, + DATA_OPTIONAL_BOSS = 3, + DATA_OPERA_PERFORMANCE = 4, + DATA_CURATOR = 5, + DATA_ARAN = 6, + DATA_TERESTIAN = 7, + DATA_NETHERSPITE = 8, + DATA_CHESS = 9, + DATA_MALCHEZZAR = 10, + DATA_NIGHTBANE = 11, - DATA_OPERA_PERFORMANCE = 13, DATA_OPERA_OZ_DEATHCOUNT = 14, DATA_KILREK = 15, - DATA_TERESTIAN = 16, - DATA_MOROES = 17, DATA_GO_CURTAINS = 18, DATA_GO_STAGEDOORLEFT = 19, DATA_GO_STAGEDOORRIGHT = 20, @@ -69,6 +68,11 @@ enum MiscCreatures NPC_HYAKISS_THE_LURKER = 16179, NPC_ROKAD_THE_RAVAGER = 16181, NPC_SHADIKITH_THE_GLIDER = 16180, + NPC_TERESTIAN_ILLHOOF = 15688, + NPC_MOROES = 15687, + NPC_ATTUMEN_UNMOUNTED = 15550, + NPC_ATTUMEN_MOUNTED = 16152, + NPC_MIDNIGHT = 16151, // Trash NPC_COLDMIST_WIDOW = 16171, @@ -78,6 +82,29 @@ enum MiscCreatures NPC_GREATER_SHADOWBAT = 16174, NPC_PHASE_HOUND = 16178, NPC_DREADBEAST = 16177, - NPC_SHADOWBEAST = 16176 + NPC_SHADOWBEAST = 16176, + NPC_KILREK = 17229 +}; + +enum GameObjectIds +{ + GO_STAGE_CURTAIN = 183932, + GO_STAGE_DOOR_LEFT = 184278, + GO_STAGE_DOOR_RIGHT = 184279, + GO_PRIVATE_LIBRARY_DOOR = 184517, + GO_MASSIVE_DOOR = 185521, + GO_GAMESMAN_HALL_DOOR = 184276, + GO_GAMESMAN_HALL_EXIT_DOOR = 184277, + GO_NETHERSPACE_DOOR = 185134, + GO_MASTERS_TERRACE_DOOR = 184274, + GO_MASTERS_TERRACE_DOOR2 = 184280, + GO_SIDE_ENTRANCE_DOOR = 184275, + GO_DUST_COVERED_CHEST = 185119 }; + +enum Misc +{ + OPTIONAL_BOSS_REQUIRED_DEATH_COUNT = 50 +}; + #endif diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp index b809128e731..ebe406c8909 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp @@ -405,7 +405,7 @@ public: Creature* Orb = DoSpawnCreature(CREATURE_ARCANE_SPHERE, 5, 5, 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 30000); if (Orb && target) { - Orb->SetSpeed(MOVE_RUN, 0.5f); + Orb->SetSpeedRate(MOVE_RUN, 0.5f); Orb->AddThreat(target, 1000000.0f); Orb->AI()->AttackStart(target); } diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp index 81044a0dbb1..3cf78b79f67 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp @@ -396,7 +396,7 @@ class npc_eye_of_acherus : public CreatureScript if (Player* owner = me->GetCharmerOrOwner()->ToPlayer()) { for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) - me->SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true); + me->SetSpeedRate(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i))); Talk(TALK_MOVE_START, owner); } me->GetMotionMaster()->MovePath(me->GetEntry() * 100, false); @@ -419,7 +419,7 @@ class npc_eye_of_acherus : public CreatureScript { owner->RemoveAura(SPELL_EYE_FLIGHT_BOOST); for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i) - me->SetSpeed(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i)), true); + me->SetSpeedRate(UnitMoveType(i), owner->GetSpeedRate(UnitMoveType(i))); Talk(TALK_CONTROL, owner); } @@ -703,7 +703,7 @@ class npc_dark_rider_of_acherus : public CreatureScript TargetGUID = who->GetGUID(); me->SetWalk(true); - me->SetSpeed(MOVE_RUN, 0.4f); + me->SetSpeedRate(MOVE_RUN, 0.4f); me->GetMotionMaster()->MoveChase(who); me->SetTarget(TargetGUID); Intro = true; @@ -1050,7 +1050,7 @@ class npc_scarlet_miner_cart : public CreatureScript // Not 100% correct, but movement is smooth. Sometimes miner walks faster // than normal, this speed is fast enough to keep up at those times. - me->SetSpeed(MOVE_RUN, 1.25f); + me->SetSpeedRate(MOVE_RUN, 1.25f); me->GetMotionMaster()->MoveFollow(miner, 1.0f, 0); } diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp index e336ff24382..ea6d2cb0b6f 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp @@ -923,7 +923,7 @@ public: if (ObjectAccessor::GetCreature(*me, uiLichKingGUID)) DoCast(me, SPELL_MOGRAINE_CHARGE); // jumping charge // doesn't make it looks well, so workarounds, Darion charges, looks better - me->SetSpeed(MOVE_RUN, 3.0f); + me->SetSpeedRate(MOVE_RUN, 3.0f); me->SetWalk(false); SetHoldState(false); JumpToNextStep(0); @@ -935,7 +935,7 @@ public: temp->HandleEmoteCommand(EMOTE_ONESHOT_KICK); temp->AI()->Talk(SAY_LIGHT_OF_DAWN46); } - me->SetSpeed(MOVE_RUN, 6.0f); + me->SetSpeedRate(MOVE_RUN, 6.0f); me->SetStandState(UNIT_STAND_STATE_DEAD); SetHoldState(false); // Darion got kicked by lich king JumpToNextStep(0); @@ -997,7 +997,7 @@ public: Unit* temp = me->SummonCreature(NPC_DEFENDER_OF_THE_LIGHT, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 10000); temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED); temp->SetWalk(false); - temp->SetSpeed(MOVE_RUN, 2.0f); + temp->SetSpeedRate(MOVE_RUN, 2.0f); temp->setFaction(me->getFaction()); temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ); uiDefenderGUID[0] = temp->GetGUID(); @@ -1005,7 +1005,7 @@ public: temp = me->SummonCreature(NPC_RIMBLAT_EARTHSHATTER, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f }), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 10000); temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED); temp->SetWalk(false); - temp->SetSpeed(MOVE_RUN, 2.0f); + temp->SetSpeedRate(MOVE_RUN, 2.0f); temp->setFaction(me->getFaction()); temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ); uiEarthshatterGUID[0] = temp->GetGUID(); @@ -1014,7 +1014,7 @@ public: { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED); temp->SetWalk(false); - temp->SetSpeed(MOVE_RUN, 2.0f); + temp->SetSpeedRate(MOVE_RUN, 2.0f); temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ); temp->AI()->Talk(SAY_LIGHT_OF_DAWN50); } @@ -1022,7 +1022,7 @@ public: { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED); temp->SetWalk(false); - temp->SetSpeed(MOVE_RUN, 2.0f); + temp->SetSpeedRate(MOVE_RUN, 2.0f); temp->HandleEmoteCommand(EMOTE_STATE_ATTACK_UNARMED); temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ); } @@ -1030,7 +1030,7 @@ public: { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_ATTACK_UNARMED); temp->SetWalk(false); - temp->SetSpeed(MOVE_RUN, 2.0f); + temp->SetSpeedRate(MOVE_RUN, 2.0f); temp->GetMotionMaster()->MovePoint(0, fLichPositionX, fLichPositionY, fLichPositionZ); } } @@ -1044,33 +1044,33 @@ public: if (Creature* temp = ObjectAccessor::GetCreature(*me, uiMaxwellGUID)) { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); - temp->SetSpeed(MOVE_RUN, 6.0f); + temp->SetSpeedRate(MOVE_RUN, 6.0f); temp->SetStandState(UNIT_STAND_STATE_DEAD); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[14]); } if (Creature* temp = ObjectAccessor::GetCreature(*me, uiKorfaxGUID)) { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); - temp->SetSpeed(MOVE_RUN, 6.0f); + temp->SetSpeedRate(MOVE_RUN, 6.0f); temp->SetStandState(UNIT_STAND_STATE_DEAD); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[11]); } if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEligorGUID)) { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); - temp->SetSpeed(MOVE_RUN, 6.0f); + temp->SetSpeedRate(MOVE_RUN, 6.0f); temp->SetStandState(UNIT_STAND_STATE_DEAD); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[17]); } if (Creature* temp = ObjectAccessor::GetCreature(*me, uiDefenderGUID[0])) { - temp->SetSpeed(MOVE_RUN, 6.0f); + temp->SetSpeedRate(MOVE_RUN, 6.0f); temp->SetStandState(UNIT_STAND_STATE_DEAD); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f })); } if (Creature* temp = ObjectAccessor::GetCreature(*me, uiEarthshatterGUID[0])) { - temp->SetSpeed(MOVE_RUN, 6.0f); + temp->SetSpeedRate(MOVE_RUN, 6.0f); temp->SetStandState(UNIT_STAND_STATE_DEAD); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[0].GetPositionWithOffset({ float(rand32() % 10), float(rand32() % 10), 0.0f, 0.0f })); } @@ -1093,7 +1093,7 @@ public: break; case 46: // Darion stand up, "not today" - me->SetSpeed(MOVE_RUN, 1.0f); + me->SetSpeedRate(MOVE_RUN, 1.0f); me->SetWalk(true); me->SetStandState(UNIT_STAND_STATE_STAND); Talk(SAY_LIGHT_OF_DAWN53); @@ -1116,7 +1116,7 @@ public: case 48: // Show the cleansing effect (dawn of light) //if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID)) // go->SetPhaseMask(128, true); - me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0, 0, 0, 0, 0, 30); + me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0.f, G3D::Quat(), 30); if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) { if (temp->HasAura(SPELL_REBIRTH_OF_THE_ASHBRINGER)) @@ -1153,7 +1153,7 @@ public: temp->AI()->Talk(EMOTE_LIGHT_OF_DAWN16); temp->CastSpell(temp, SPELL_TIRION_CHARGE, false); // jumping charge temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H); - temp->SetSpeed(MOVE_RUN, 3.0f); // workarounds, make Tirion still running + temp->SetSpeedRate(MOVE_RUN, 3.0f); // workarounds, make Tirion still running temp->SetWalk(false); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[2]); if (Creature* lktemp = ObjectAccessor::GetCreature(*me, uiLichKingGUID)) @@ -1171,7 +1171,7 @@ public: case 54: if (Creature* temp = ObjectAccessor::GetCreature(*me, uiLichKingGUID)) { - temp->SetSpeed(MOVE_RUN, 1.0f); + temp->SetSpeedRate(MOVE_RUN, 1.0f); me->SetWalk(true); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[29]); // 26 } @@ -1208,7 +1208,7 @@ public: if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) // Tirion runs to Darion { temp->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); - temp->SetSpeed(MOVE_RUN, 1.0f); + temp->SetSpeedRate(MOVE_RUN, 1.0f); temp->GetMotionMaster()->MovePoint(0, LightofDawnLoc[6]); } JumpToNextStep(2500); diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp index 53b6d2be8dd..9abd0c049d8 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp @@ -109,7 +109,7 @@ public: FlyBackTimer = 4500; break; case 2: - if (!player->isResurrectRequested()) + if (!player->IsResurrectRequested()) { me->HandleEmoteCommand(EMOTE_ONESHOT_CUSTOM_SPELL_01); DoCast(player, SPELL_REVIVE, true); diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp index dff0a66cec0..734b70933aa 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp @@ -134,8 +134,6 @@ static char const* Text[]= "Now, know demise!" }; -#define EMOTE_LAUGHS "Headless Horseman laughs" // needs assigned to db. - class npc_wisp_invis : public CreatureScript { public: @@ -347,7 +345,6 @@ public: Creature* speaker = DoSpawnCreature(HELPER, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 1000); if (speaker) speaker->CastSpell(speaker, SPELL_HEAD_SPEAKS, false); - me->TextEmote(EMOTE_LAUGHS); } else laugh -= diff; } @@ -453,7 +450,7 @@ public: me->SetVisible(false); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->SetDisableGravity(true); - me->SetSpeed(MOVE_WALK, 5.0f, true); + me->SetSpeedRate(MOVE_WALK, 5.0f); wp_reached = false; count = 0; say_timer = 3000; @@ -724,7 +721,6 @@ public: if (laugh <= diff) { laugh = urand(11000, 22000); - me->TextEmote(EMOTE_LAUGHS); DoPlaySoundToSet(me, RandomLaugh[rand32() % 3]); } else laugh -= diff; @@ -898,12 +894,12 @@ public: if (instance->GetBossState(DATA_HORSEMAN_EVENT) == IN_PROGRESS) return false; - player->AreaExploredOrEventHappens(11405); - if (Creature* horseman = go->SummonCreature(HH_MOUNTED, FlightPoint[20].x, FlightPoint[20].y, FlightPoint[20].z, 0, TEMPSUMMON_MANUAL_DESPAWN, 0)) - { - ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->PlayerGUID = player->GetGUID(); - ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->FlyMode(); - } + player->AreaExploredOrEventHappens(11405); + if (Creature* horseman = go->SummonCreature(HH_MOUNTED, FlightPoint[20].x, FlightPoint[20].y, FlightPoint[20].z, 0, TEMPSUMMON_MANUAL_DESPAWN, 0)) + { + ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->PlayerGUID = player->GetGUID(); + ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->FlyMode(); + } return true; } }; diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp index 118d28e2142..241710627b0 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp @@ -35,15 +35,25 @@ enum Gameobject GO_ATALAI_STATUE4 = 148833, GO_ATALAI_STATUE5 = 148834, GO_ATALAI_STATUE6 = 148835, - GO_ATALAI_IDOL = 148836, GO_ATALAI_LIGHT1 = 148883, GO_ATALAI_LIGHT2 = 148937 - }; enum CreatureIds { - NPC_MALFURION_STORMRAGE = 15362 + NPC_ATALALARION = 8580 +}; + +static Position const atalalarianPos = { -466.5134f, 95.19822f, -189.6463f, 0.03490658f }; +static uint8 const nStatues = 6; +static Position const statuePositions[nStatues] +{ + { -515.553f, 95.25821f, -173.707f, 0.0f }, + { -419.8487f, 94.48368f, -173.707f, 0.0f }, + { -491.4003f, 135.9698f, -173.707f, 0.0f }, + { -491.4909f, 53.48179f, -173.707f, 0.0f }, + { -443.8549f, 136.1007f, -173.707f, 0.0f }, + { -443.4171f, 53.83124f, -173.707f, 0.0f } }; class instance_sunken_temple : public InstanceMapScript @@ -77,7 +87,6 @@ public: ObjectGuid GOAtalaiStatue4; ObjectGuid GOAtalaiStatue5; ObjectGuid GOAtalaiStatue6; - ObjectGuid GOAtalaiIdol; uint32 State; @@ -98,7 +107,6 @@ public: case GO_ATALAI_STATUE4: GOAtalaiStatue4 = go->GetGUID(); break; case GO_ATALAI_STATUE5: GOAtalaiStatue5 = go->GetGUID(); break; case GO_ATALAI_STATUE6: GOAtalaiStatue6 = go->GetGUID(); break; - case GO_ATALAI_IDOL: GOAtalaiIdol = go->GetGUID(); break; } } @@ -155,7 +163,10 @@ public: if (s1 && s2 && s3 && s4 && s5 && !s6) { if (GameObject* pAtalaiStatue6 = instance->GetGameObject(GOAtalaiStatue6)) + { UseStatue(pAtalaiStatue6); + UseLastStatue(pAtalaiStatue6); + } s6 = true; State = 0; } @@ -165,22 +176,17 @@ public: void UseStatue(GameObject* go) { - go->SummonGameObject(GO_ATALAI_LIGHT1, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, 0, 0, 0, 0, 0); + go->SummonGameObject(GO_ATALAI_LIGHT1, *go, G3D::Quat(), 0); go->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } - /* - void UseLastStatue(GameObject* go) - { - AtalaiStatue1->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue1->GetPositionX(), AtalaiStatue1->GetPositionY(), AtalaiStatue1->GetPositionZ(), 0, 0, 0, 0, 0, 100); - AtalaiStatue2->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue2->GetPositionX(), AtalaiStatue2->GetPositionY(), AtalaiStatue2->GetPositionZ(), 0, 0, 0, 0, 0, 100); - AtalaiStatue3->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue3->GetPositionX(), AtalaiStatue3->GetPositionY(), AtalaiStatue3->GetPositionZ(), 0, 0, 0, 0, 0, 100); - AtalaiStatue4->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue4->GetPositionX(), AtalaiStatue4->GetPositionY(), AtalaiStatue4->GetPositionZ(), 0, 0, 0, 0, 0, 100); - AtalaiStatue5->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue5->GetPositionX(), AtalaiStatue5->GetPositionY(), AtalaiStatue5->GetPositionZ(), 0, 0, 0, 0, 0, 100); - AtalaiStatue6->SummonGameObject(GO_ATALAI_LIGHT2, AtalaiStatue6->GetPositionX(), AtalaiStatue6->GetPositionY(), AtalaiStatue6->GetPositionZ(), 0, 0, 0, 0, 0, 100); - go->SummonGameObject(148838, -488.997, 96.61, -189.019, -1.52, 0, 0, 0, 0, 100); - } - */ + void UseLastStatue(GameObject* go) + { + for (uint8 i = 0; i < nStatues; ++i) + go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i], G3D::Quat(), 0); + + go->SummonCreature(NPC_ATALALARION, atalalarianPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200); + } void SetData(uint32 type, uint32 data) override { diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp index d9b481d7b6d..fded249f9ca 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp @@ -249,7 +249,7 @@ public: me->CastStop(SPELL_FOG_BREATH); me->RemoveAurasDueToSpell(SPELL_FOG_BREATH); me->StopMoving(); - me->SetSpeed(MOVE_RUN, 2.0f); + me->SetSpeedRate(MOVE_RUN, 2.0f); events.ScheduleEvent(EVENT_CLEAVE, urand(5000, 10000)); events.ScheduleEvent(EVENT_CORROSION, urand(10000, 20000)); @@ -530,7 +530,7 @@ public: npc_felmyst_vaporAI(Creature* creature) : ScriptedAI(creature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetSpeed(MOVE_RUN, 0.8f); + me->SetSpeedRate(MOVE_RUN, 0.8f); } void Reset() override { } diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp index d86b3707606..040d8cb2a37 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp @@ -143,11 +143,7 @@ enum Spells SPELL_RING_OF_BLUE_FLAMES = 45825 //Cast this spell when the go is activated }; -/*** Error messages ***/ -#define ERROR_KJ_NOT_SUMMONED "TSCR ERROR: Unable to summon Kil'Jaeden for some reason" - /*** Others ***/ -#define FLOOR_Z 28.050388f #define SHIELD_ORB_Z 45.000f enum Phase @@ -1365,7 +1361,7 @@ public: DoCastVictim(SPELL_SR_SHOOT, false); uiTimer[2] = urand(4000, 6000); } - if (me->IsWithinMeleeRange(me->GetVictim(), 6)) + if (me->IsWithinMeleeRange(me->GetVictim())) { if (uiTimer[0] <= diff) { diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp index 04d23cd7d4e..6c84677708e 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp @@ -15,88 +15,119 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -/* ScriptData -SDName: Boss_Muru -SD%Complete: 80 -SDComment: all sounds, black hole effect triggers to often (46228) -*/ - #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" -#include "Player.h" -#include "SpellInfo.h" +#include "SpellScript.h" +#include "SpellAuraEffects.h" -// Muru & Entropius's spells enum Spells { - SPELL_ENRAGE = 26662, - // Muru's spells - SPELL_NEGATIVE_ENERGY = 46009, //(this trigger 46008) - SPELL_DARKNESS = 45999, - SPELL_OPEN_ALL_PORTALS = 46177, - SPELL_OPEN_PORTAL = 45977, - SPELL_OPEN_PORTAL_2 = 45976, - SPELL_SUMMON_BERSERKER = 46037, - SPELL_SUMNON_FURY_MAGE = 46038, - SPELL_SUMMON_VOID_SENTINEL = 45988, - SPELL_SUMMON_ENTROPIUS = 46217, + SPELL_OPEN_PORTAL_PERIODIC = 45994, + SPELL_DARKNESS_PERIODIC = 45998, + SPELL_NEGATIVE_ENERGY_PERIODIC = 46009, + SPELL_SUMMON_VOID_SPAWN = 46071, + SPELL_SUMMON_BLOOD_ELVES_SCRIPT = 46050, + SPELL_SUMMON_BLOOD_ELVES_PERIODIC = 46041, + SPELL_OPEN_ALL_PORTALS = 46177, + SPELL_SUMMON_ENTROPIUS = 46217, + SPELL_ENRAGE = 26662, + SPELL_SUMMON_DARK_FIEND_0 = 46000, + SPELL_SUMMON_DARK_FIEND_1 = 46001, + SPELL_SUMMON_DARK_FIEND_2 = 46002, + SPELL_SUMMON_DARK_FIEND_3 = 46003, + SPELL_SUMMON_DARK_FIEND_4 = 46004, + SPELL_SUMMON_DARK_FIEND_5 = 46005, + SPELL_SUMMON_DARK_FIEND_6 = 46006, + SPELL_SUMMON_DARK_FIEND_7 = 46007, + SPELL_SUMMON_BERSERKER = 46037, + SPELL_SUMMON_BERSERKER_2 = 46040, + SPELL_SUMMON_FURY_MAGE = 46038, + SPELL_SUMMON_FURY_MAGE_2 = 46039, // Entropius's spells - SPELL_DARKNESS_E = 46269, - SPELL_BLACKHOLE = 46282, - SPELL_NEGATIVE_ENERGY_E = 46284, - SPELL_ENTROPIUS_SPAWN = 46223, - - // Shadowsword Berserker's spells - SPELL_FLURRY = 46160, - SPELL_DUAL_WIELD = 29651, + SPELL_ENTROPIUS_COSMETIC_SPAWN = 46223, + SPELL_DARKNESS_E = 46269, + SPELL_NEGATIVE_ENERGY_PERIODIC_E = 46284, + SPELL_BLACKHOLE = 46282, + SPELL_SUMMON_DARKFIEND_E = 46263, + + // Myruu's Portal Target + SPELL_SUMMON_VOID_SENTINEL_SUMMONER = 45978, + SPELL_SUMMON_VOID_SENTINEL_SUMMONER_VISUAL = 45989, + SPELL_SUMMON_VOID_SENTINEL = 45988, + SPELL_TRANSFORM_VISUAL_MISSILE = 46205, + TRANSFORM_VISUAL_MISSILE_1 = 46208, + TRANSFORM_VISUAL_MISSILE_2 = 46178, + SPELL_OPEN_PORTAL = 45977, + SPELL_OPEN_PORTAL_2 = 45976, - // Shadowsword Fury Mage's spells - SPELL_FEL_FIREBALL = 46101, - SPELL_SPELL_FURY = 46102, + //Dark Fiend Spells + SPELL_DARKFIEND_DAMAGE = 45944, + SPELL_DARKFIEND_VISUAL = 45936, + SPELL_DARKFIEND_SKIN = 45934, // Void Sentinel's spells - SPELL_SHADOW_PULSE = 46087, - SPELL_VOID_BLAST = 46161, + SPELL_SHADOW_PULSE_PERIODIC = 46086, + SPELL_VOID_BLAST = 46161, - // Void Spawn's spells - SPELL_SHADOW_BOLT_VOLLEY = 46082, + //Black Hole Spells + SPELL_BLACKHOLE_SUMMON_VISUAL = 46242, + SPELL_BLACKHOLE_SUMMON_VISUAL_2 = 46247, + SPELL_BLACKHOLE_PASSIVE = 46228, + SPELL_BLACK_HOLE_VISUAL_2 = 46235 +}; - //Dark Fiend Spells - SPELL_DARKFIEND_AOE = 45944, - SPELL_DARKFIEND_VISUAL = 45936, - SPELL_DARKFIEND_SKIN = 45934, +enum Phases +{ + PHASE_ONE = 1, + PHASE_TWO = 2 +}; - //Black Hole Spells - SPELL_BLACKHOLE_SPAWN = 46242, - SPELL_BLACKHOLE_GROW = 46228 +enum Misc +{ + MAX_VOID_SPAWNS = 6, + MAX_SUMMON_BLOOD_ELVES = 4, + MAX_SUMMON_DARK_FIEND = 8 }; -enum Events +uint32 const SummonDarkFiendSpells[MAX_SUMMON_DARK_FIEND] = { - // M'uru - EVENT_DARKNESS = 1, - EVENT_SUMMON_HUMANOIDS, - EVENT_SUMMON_SENTINEL, - EVENT_PHASE_TRANSITION, // Delayed phase transition. - EVENT_ENRAGE, - - // Entropius - EVENT_SUMMON_BLACK_HOLE + SPELL_SUMMON_DARK_FIEND_0, + SPELL_SUMMON_DARK_FIEND_1, + SPELL_SUMMON_DARK_FIEND_2, + SPELL_SUMMON_DARK_FIEND_3, + SPELL_SUMMON_DARK_FIEND_4, + SPELL_SUMMON_DARK_FIEND_5, + SPELL_SUMMON_DARK_FIEND_6, + SPELL_SUMMON_DARK_FIEND_7 }; -enum Phases +uint32 const SummonBloodElvesSpells[MAX_SUMMON_BLOOD_ELVES] = { - PHASE_ONE = 1, - PHASE_TWO, + SPELL_SUMMON_BERSERKER, + SPELL_SUMMON_BERSERKER_2, + SPELL_SUMMON_FURY_MAGE, + SPELL_SUMMON_FURY_MAGE_2 }; -enum CreatureGroups +class VoidSpawnSummon : public BasicEvent { - CREATURE_GROUP_HUMANOIDS, - CREATURE_GROUP_DARKFIENDS + public: + explicit VoidSpawnSummon(Creature* owner) + : _owner(owner) + { + } + + bool Execute(uint64 /*time*/, uint32 /*diff*/) + { + _owner->CastSpell((Unit*)nullptr, SPELL_SUMMON_VOID_SENTINEL, true); + return true; + } + + private: + Creature* _owner; }; class boss_entropius : public CreatureScript @@ -110,53 +141,78 @@ public: void Reset() override { - DoCastAOE(SPELL_NEGATIVE_ENERGY_E); + _Reset(); + DoCast(me, SPELL_ENTROPIUS_COSMETIC_SPAWN, true); } - void EnterCombat(Unit* /*who*/) override + void ScheduleTasks() override { - _EnterCombat(); - DoCastAOE(SPELL_NEGATIVE_ENERGY_E, true); - DoCast(me, SPELL_ENTROPIUS_SPAWN); - events.ScheduleEvent(EVENT_SUMMON_BLACK_HOLE, 15000); + scheduler.Schedule(Milliseconds(2000), [this](TaskContext /*context*/) + { + DoResetPortals(); + DoCastAOE(SPELL_NEGATIVE_ENERGY_PERIODIC_E, true); + }); + + scheduler.Schedule(Seconds(15), [this](TaskContext context) + { + DoCastAOE(SPELL_DARKNESS_E, true); + DoCastAOE(SPELL_BLACKHOLE, true); + + context.Repeat(); + }); } - void JustSummoned(Creature* summoned) override + void JustSummoned(Creature* summon) override { - switch (summoned->GetEntry()) + switch (summon->GetEntry()) { case NPC_DARK_FIENDS: - summoned->CastSpell(summoned, SPELL_DARKFIEND_VISUAL); + summon->CastSpell(summon, SPELL_DARKFIEND_VISUAL); break; case NPC_DARKNESS: - summoned->AddUnitState(UNIT_STATE_STUNNED); - float x, y, z, o; - summoned->GetHomePosition(x, y, z, o); - me->SummonCreature(NPC_DARK_FIENDS, x, y, z, o, TEMPSUMMON_CORPSE_DESPAWN, 0); + summon->SetReactState(REACT_PASSIVE); + summon->CastSpell(summon, SPELL_BLACKHOLE); + summon->CastSpell(summon, SPELL_SUMMON_DARKFIEND_E, true); break; } - summoned->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 50, true)); - summons.Summon(summoned); + summons.Summon(summon); } - void ExecuteEvent(uint32 eventId) override + void EnterEvadeMode(EvadeReason /*why*/) override { - if (eventId == EVENT_SUMMON_BLACK_HOLE) - { - if (Unit* random = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) - DoCast(random, SPELL_DARKNESS_E); - if (Unit* random = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) - random->CastSpell(random, SPELL_BLACKHOLE); - events.ScheduleEvent(EVENT_SUMMON_BLACK_HOLE, 15000); - } + if (Creature* muru = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_MURU))) + muru->AI()->EnterEvadeMode(); + + DoResetPortals(); + summons.DespawnAll(); + me->DespawnOrUnsummon(); } - void EnterEvadeMode(EvadeReason /*why*/) override + void JustDied(Unit* /*killer*/) override { + _JustDied(); + if (Creature* muru = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_MURU))) - muru->AI()->Reset(); // Reset encounter. - me->DisappearAndDie(); - summons.DespawnAll(); + muru->DisappearAndDie(); + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + scheduler.Update(diff, [this] + { + DoMeleeAttackIfReady(); + }); + } + + void DoResetPortals() + { + std::list<Creature*> portals; + me->GetCreatureListWithEntryInGrid(portals, NPC_MURU_PORTAL_TARGET, 100.0f); + for (Creature* portal : portals) + portal->RemoveAllAuras(); } }; @@ -181,101 +237,96 @@ public: void Initialize() { - DarkFiend = false; - HasEnraged = false; - EntropiusGUID.Clear(); + _hasEnraged = false; + _phase = PHASE_ONE; + _entropiusGUID.Clear(); } void Reset() override { - Initialize(); _Reset(); + Initialize(); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->SetVisible(true); } + void EnterEvadeMode(EvadeReason /*why*/) override + { + BossAI::EnterEvadeMode(); + if (Creature* entropius = ObjectAccessor::GetCreature(*me, _entropiusGUID)) + entropius->AI()->EnterEvadeMode(); + } + + void ScheduleTasks() override + { + scheduler.Schedule(Minutes(10), [this](TaskContext /*context*/) + { + if (Creature* entropius = ObjectAccessor::GetCreature(*me, _entropiusGUID)) + entropius->CastSpell(entropius, SPELL_ENRAGE); + DoCast(me, SPELL_ENRAGE); + _hasEnraged = true; + }); + + scheduler.Schedule(Seconds(10), [this](TaskContext /*context*/) + { + DoCast(me, SPELL_SUMMON_BLOOD_ELVES_SCRIPT, true); + DoCast(me, SPELL_SUMMON_BLOOD_ELVES_PERIODIC, true); + }); + } + void EnterCombat(Unit* /*who*/) override { _EnterCombat(); - events.SetPhase(PHASE_ONE); - events.ScheduleEvent(EVENT_ENRAGE, 600000); - events.ScheduleEvent(EVENT_DARKNESS, 45000, 0, PHASE_ONE); - events.ScheduleEvent(EVENT_SUMMON_HUMANOIDS, 10000, 0, PHASE_ONE); - events.ScheduleEvent(EVENT_SUMMON_SENTINEL, 31500, 0, PHASE_ONE); - DoCastAOE(SPELL_NEGATIVE_ENERGY); + DoCast(me, SPELL_OPEN_PORTAL_PERIODIC, true); + DoCast(me, SPELL_DARKNESS_PERIODIC, true); + DoCast(me, SPELL_NEGATIVE_ENERGY_PERIODIC, true); } void DamageTaken(Unit* /*done_by*/, uint32 &damage) override { - if (damage >= me->GetHealth() && events.IsInPhase(PHASE_ONE)) + if (damage >= me->GetHealth()) { - damage = 0; + damage = me->GetHealth() - 1; + if (_phase != PHASE_ONE) + return; + + _phase = PHASE_TWO; me->RemoveAllAuras(); - DoCast(me, SPELL_OPEN_ALL_PORTALS); + DoCast(me, SPELL_OPEN_ALL_PORTALS, true); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - events.SetPhase(PHASE_TWO); - events.ScheduleEvent(EVENT_PHASE_TRANSITION, 2000); + + scheduler.Schedule(Seconds(6), [this](TaskContext /*context*/) + { + DoCast(me, SPELL_SUMMON_ENTROPIUS, true); + }); } } - void JustSummoned(Creature* summoned) override + void JustSummoned(Creature* summon) override { - switch (summoned->GetEntry()) + if (summon->GetEntry() == NPC_ENTROPIUS) { - case NPC_ENTROPIUS: - me->SetVisible(false); - EntropiusGUID = summoned->GetGUID(); - if (HasEnraged) // If we hit phase transition while enraged, enrage Entropius as well. - summoned->CastSpell(summoned, SPELL_ENRAGE); - break; - case NPC_DARK_FIENDS: - summoned->CastSpell(summoned, SPELL_DARKFIEND_VISUAL); - break; + me->SetVisible(false); + _entropiusGUID = summon->GetGUID(); + if (_hasEnraged) + summon->CastSpell(summon, SPELL_ENRAGE, true); + return; } - summoned->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 50, true)); - summons.Summon(summoned); + BossAI::JustSummoned(summon); } - void ExecuteEvent(uint32 eventId) override + void UpdateAI(uint32 diff) override { - switch (eventId) - { - case EVENT_DARKNESS: - if (!DarkFiend) - { - DarkFiend = true; - DoCastAOE(SPELL_DARKNESS); - } - else - me->SummonCreatureGroup(CREATURE_GROUP_DARKFIENDS); - events.ScheduleEvent(EVENT_DARKNESS, DarkFiend ? 3000 : 42000, 0, PHASE_ONE); - break; - case EVENT_SUMMON_HUMANOIDS: - me->SummonCreatureGroup(CREATURE_GROUP_HUMANOIDS); - events.ScheduleEvent(EVENT_SUMMON_HUMANOIDS, 60000, 0, PHASE_ONE); - break; - case EVENT_SUMMON_SENTINEL: - DoCastAOE(SPELL_OPEN_PORTAL_2); - events.ScheduleEvent(EVENT_SUMMON_SENTINEL, 30000, 0, PHASE_ONE); - break; - case EVENT_PHASE_TRANSITION: - DoCast(me, SPELL_SUMMON_ENTROPIUS); - break; - case EVENT_ENRAGE: - if (Creature* entropius = ObjectAccessor::GetCreature(*me, EntropiusGUID)) - entropius->CastSpell(entropius, SPELL_ENRAGE); - DoCast(me, SPELL_ENRAGE); - HasEnraged = true; - break; - default: - break; - } + if (!UpdateVictim()) + return; + + scheduler.Update(diff); } private: - bool DarkFiend; - bool HasEnraged; - ObjectGuid EntropiusGUID; + ObjectGuid _entropiusGUID; + bool _hasEnraged; + uint8 _phase; }; CreatureAI* GetAI(Creature* creature) const override @@ -289,89 +340,50 @@ class npc_muru_portal : public CreatureScript public: npc_muru_portal() : CreatureScript("npc_muru_portal") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI<npc_muru_portalAI>(creature); - } - struct npc_muru_portalAI : public ScriptedAI { - npc_muru_portalAI(Creature* creature) : ScriptedAI(creature), Summons(creature) - { - Initialize(); - SetCombatMovement(false); - instance = creature->GetInstanceScript(); - } - - void Initialize() - { - SummonTimer = 5000; - - InAction = false; - SummonSentinel = false; - } - - InstanceScript* instance; - - SummonList Summons; - - bool SummonSentinel; - bool InAction; - - uint32 SummonTimer; - - void Reset() override - { - Initialize(); + npc_muru_portalAI(Creature* creature) : ScriptedAI(creature) { } - me->AddUnitState(UNIT_STATE_STUNNED); - - Summons.DespawnAll(); - } - - void JustSummoned(Creature* summoned) override + void JustSummoned(Creature* summon) override { - if (Player* target = ObjectAccessor::GetPlayer(*me, instance->GetGuidData(DATA_PLAYER_GUID))) - summoned->AI()->AttackStart(target); + DoCast(summon, SPELL_SUMMON_VOID_SENTINEL_SUMMONER_VISUAL, true); - Summons.Summon(summoned); + summon->m_Events.AddEvent(new VoidSpawnSummon(summon), summon->m_Events.CalculateTime(1500)); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { - float x, y, z, o; - me->GetHomePosition(x, y, z, o); - me->NearTeleportTo(x, y, z, o); - InAction = true; - switch (Spell->Id) + switch (spell->Id) { case SPELL_OPEN_ALL_PORTALS: - DoCastAOE(SPELL_OPEN_PORTAL); + DoCastAOE(SPELL_OPEN_PORTAL, true); + DoCastAOE(SPELL_TRANSFORM_VISUAL_MISSILE, true); break; case SPELL_OPEN_PORTAL_2: - DoCastAOE(SPELL_OPEN_PORTAL); - SummonSentinel = true; + DoCastAOE(SPELL_OPEN_PORTAL, true); + _scheduler.Schedule(Seconds(6), [this](TaskContext /*context*/) + { + DoCastAOE(SPELL_SUMMON_VOID_SENTINEL_SUMMONER, true); + }); + break; + default: break; } } void UpdateAI(uint32 diff) override { - if (!SummonSentinel) - { - if (InAction && instance->GetBossState(DATA_MURU) == NOT_STARTED) - Reset(); - return; - } - - if (SummonTimer <= diff) - { - DoCastAOE(SPELL_SUMMON_VOID_SENTINEL, false); - SummonTimer = 5000; - SummonSentinel = false; - } else SummonTimer -= diff; + _scheduler.Update(diff); } + + private: + TaskScheduler _scheduler; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI<npc_muru_portalAI>(creature); + } }; class npc_dark_fiend : public CreatureScript @@ -379,11 +391,6 @@ class npc_dark_fiend : public CreatureScript public: npc_dark_fiend() : CreatureScript("npc_dark_fiend") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_dark_fiendAI(creature); - } - struct npc_dark_fiendAI : public ScriptedAI { npc_dark_fiendAI(Creature* creature) : ScriptedAI(creature) @@ -393,54 +400,56 @@ public: void Initialize() { - WaitTimer = 2000; - InAction = false; - } + me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); + me->SetReactState(REACT_PASSIVE); + DoCast(me, SPELL_DARKFIEND_SKIN, true); - uint32 WaitTimer; - bool InAction; + _scheduler.Schedule(Seconds(2), [this](TaskContext /*context*/) + { + me->SetReactState(REACT_AGGRESSIVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - void Reset() override - { - Initialize(); + if (Creature* _summoner = ObjectAccessor::GetCreature(*me, _summonerGUID)) + if (Unit* target = _summoner->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0)) + AttackStart(target); + }); - me->AddUnitState(UNIT_STATE_STUNNED); + _scheduler.Schedule(Seconds(3), [this](TaskContext context) + { + if (me->IsWithinDist(me->GetVictim(), 5.0f) && me->HasAura(SPELL_DARKFIEND_SKIN)) + { + DoCastAOE(SPELL_DARKFIEND_DAMAGE, false); + me->DisappearAndDie(); + } + + context.Repeat(Milliseconds(500)); + }); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void IsSummonedBy(Unit* summoner) override { - for (uint8 i = 0; i < 3; ++i) - if (Spell->Effects[i].Effect == 38) - me->DisappearAndDie(); + _summonerGUID = summoner->GetGUID(); } - void UpdateAI(uint32 diff) override + bool CanAIAttack(Unit const* /*target*/) const override { - if (!UpdateVictim()) - return; + return me->HasAura(SPELL_DARKFIEND_SKIN); + } - if (WaitTimer <= diff) - { - if (!InAction) - { - me->ClearUnitState(UNIT_STATE_STUNNED); - DoCastAOE(SPELL_DARKFIEND_SKIN, false); - AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)); - InAction = true; - WaitTimer = 500; - } - else - { - if (me->IsWithinDist(me->GetVictim(), 5)) - { - DoCastAOE(SPELL_DARKFIEND_AOE, false); - me->DisappearAndDie(); - } - WaitTimer = 500; - } - } else WaitTimer -= diff; + void UpdateAI(uint32 diff) override + { + _scheduler.Update(diff); } + + private: + TaskScheduler _scheduler; + ObjectGuid _summonerGUID; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI<npc_dark_fiendAI>(creature); + } }; class npc_void_sentinel : public CreatureScript @@ -448,63 +457,54 @@ class npc_void_sentinel : public CreatureScript public: npc_void_sentinel() : CreatureScript("npc_void_sentinel") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_void_sentinelAI(creature); - } - struct npc_void_sentinelAI : public ScriptedAI { npc_void_sentinelAI(Creature* creature) : ScriptedAI(creature) { - Initialize(); + _instance = me->GetInstanceScript(); } - void Initialize() + void IsSummonedBy(Unit* /*summoner*/) override { - PulseTimer = 3000; - VoidBlastTimer = 45000; //is this a correct timer? + if (Creature* muru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_MURU))) + muru->AI()->JustSummoned(me); } - uint32 PulseTimer; - uint32 VoidBlastTimer; - - void Reset() override + void EnterCombat(Unit* /*who*/) override { - Initialize(); + DoCast(me, SPELL_SHADOW_PULSE_PERIODIC, true); - float x, y, z, o; - me->GetHomePosition(x, y, z, o); - me->NearTeleportTo(x, y, 71, o); + _scheduler.Schedule(Seconds(45), [this](TaskContext context) + { + DoCastVictim(SPELL_VOID_BLAST, false); + + context.Repeat(); + }); } - void JustDied(Unit* killer) override + void JustDied(Unit* /*killer*/) override { - for (uint8 i = 0; i < 8; ++i) - if (Creature* temp = me->SummonCreature(NPC_VOID_SPAWN, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), float(rand32() % 6), TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 180000)) - temp->AI()->AttackStart(killer); + for (uint8 i = 0; i < MAX_VOID_SPAWNS; ++i) + DoCastAOE(SPELL_SUMMON_VOID_SPAWN, true); } void UpdateAI(uint32 diff) override { - if (!UpdateVictim()) - return; - - if (PulseTimer <= diff) - { - DoCastAOE(SPELL_SHADOW_PULSE, true); - PulseTimer = 3000; - } else PulseTimer -= diff; - - if (VoidBlastTimer <= diff) + _scheduler.Update(diff, [this] { - DoCastVictim(SPELL_VOID_BLAST, false); - VoidBlastTimer = 45000; - } else VoidBlastTimer -= diff; - - DoMeleeAttackIfReady(); + DoMeleeAttackIfReady(); + }); } + + private: + TaskScheduler _scheduler; + InstanceScript* _instance; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI<npc_void_sentinelAI>(creature); + } }; class npc_blackhole : public CreatureScript @@ -512,84 +512,220 @@ class npc_blackhole : public CreatureScript public: npc_blackhole() : CreatureScript("npc_blackhole") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI<npc_blackholeAI>(creature); - } - struct npc_blackholeAI : public ScriptedAI { npc_blackholeAI(Creature* creature) : ScriptedAI(creature) { - Initialize(); - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } - void Initialize() - { - DespawnTimer = 15000; - SpellTimer = 5000; - Phase = 0; - NeedForAHack = 0; - } - - InstanceScript* instance; - - uint32 DespawnTimer; - uint32 SpellTimer; - uint8 Phase; - uint8 NeedForAHack; - void Reset() override { - Initialize(); + me->SetReactState(REACT_PASSIVE); + DoCast(SPELL_BLACKHOLE_SUMMON_VISUAL); - me->AddUnitState(UNIT_STATE_STUNNED); - DoCastAOE(SPELL_BLACKHOLE_SPAWN, true); - } + _scheduler.Schedule(Seconds(15), [this](TaskContext /*context*/) + { + me->DisappearAndDie(); + }); - void UpdateAI(uint32 diff) override - { - if (SpellTimer <= diff) + _scheduler.Schedule(Seconds(1), [this](TaskContext context) { - Unit* Victim = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID)); - switch (NeedForAHack) + switch (context.GetRepeatCounter()) { case 0: - me->ClearUnitState(UNIT_STATE_STUNNED); - DoCastAOE(SPELL_BLACKHOLE_GROW, false); - if (Victim) - AttackStart(Victim); - SpellTimer = 700; - NeedForAHack = 2; + me->SetReactState(REACT_AGGRESSIVE); + DoCast(SPELL_BLACKHOLE_SUMMON_VISUAL_2); + if (Unit* victim = ObjectAccessor::GetUnit(*me, _instance->GetGuidData(DATA_PLAYER_GUID))) + AttackStart(victim); + context.Repeat(Milliseconds(1200)); break; case 1: - me->AddAura(SPELL_BLACKHOLE_GROW, me); - NeedForAHack = 2; - SpellTimer = 600; + DoCast(SPELL_BLACKHOLE_SUMMON_VISUAL); + context.Repeat(Seconds(2)); break; case 2: - SpellTimer = 400; - NeedForAHack = 3; - me->RemoveAura(SPELL_BLACKHOLE_GROW); + DoCast(SPELL_BLACKHOLE_PASSIVE); + DoCast(SPELL_BLACK_HOLE_VISUAL_2); + break; + default: break; - case 3: - SpellTimer = urand(400, 900); - NeedForAHack = 1; - if (Unit* Temp = me->GetVictim()) - { - if (Temp->GetPositionZ() > 73 && Victim) - AttackStart(Victim); - } else - return; } - } else SpellTimer -= diff; + }); + } - if (DespawnTimer <= diff) - me->DisappearAndDie(); - else DespawnTimer -= diff; + void UpdateAI(uint32 diff) override + { + _scheduler.Update(diff); } + + private: + TaskScheduler _scheduler; + InstanceScript* _instance; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI<npc_blackholeAI>(creature); + } +}; + +class spell_summon_blood_elves_script : SpellScriptLoader +{ + public: + spell_summon_blood_elves_script() : SpellScriptLoader("spell_summon_blood_elves_script") { } + + class spell_summon_blood_elves_script_SpellScript : public SpellScript + { + PrepareSpellScript(spell_summon_blood_elves_script_SpellScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + for (uint8 i = 0; i < MAX_SUMMON_BLOOD_ELVES; ++i) + if (!sSpellMgr->GetSpellInfo(SummonBloodElvesSpells[i])) + return false; + return true; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + for (uint8 i = 0; i < MAX_SUMMON_BLOOD_ELVES; ++i) + GetCaster()->CastSpell((Unit*)nullptr, SummonBloodElvesSpells[urand(0,3)], true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_summon_blood_elves_script_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_summon_blood_elves_script_SpellScript(); + } +}; + +class spell_muru_darkness : SpellScriptLoader +{ + public: + spell_muru_darkness() : SpellScriptLoader("spell_muru_darkness") { } + + class spell_muru_darkness_SpellScript : public SpellScript + { + PrepareSpellScript(spell_muru_darkness_SpellScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + for (uint8 i = 0; i < MAX_SUMMON_DARK_FIEND; ++i) + if (!sSpellMgr->GetSpellInfo(SummonDarkFiendSpells[i])) + return false; + return true; + } + + void HandleAfterCast() + { + for (uint8 i = 0; i < MAX_SUMMON_DARK_FIEND; ++i) + GetCaster()->CastSpell((Unit*)nullptr, SummonDarkFiendSpells[i], true); + } + + void Register() override + { + AfterCast += SpellCastFn(spell_muru_darkness_SpellScript::HandleAfterCast); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_muru_darkness_SpellScript(); + } +}; + +class spell_dark_fiend_skin : public SpellScriptLoader +{ + public: + spell_dark_fiend_skin() : SpellScriptLoader("spell_dark_fiend_skin") { } + + class spell_dark_fiend_skin_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dark_fiend_skin_AuraScript); + + void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + if (GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_ENEMY_SPELL) + return; + + if (Creature* target = GetTarget()->ToCreature()) + { + target->SetReactState(REACT_PASSIVE); + target->AttackStop(); + target->StopMoving(); + target->CastSpell(target, SPELL_DARKFIEND_VISUAL, true); + target->DespawnOrUnsummon(3000); + } + } + + void Register() override + { + AfterEffectRemove += AuraEffectRemoveFn(spell_dark_fiend_skin_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dark_fiend_skin_AuraScript(); + } +}; + +class spell_transform_visual_missile_periodic : public SpellScriptLoader +{ + public: + spell_transform_visual_missile_periodic() : SpellScriptLoader("spell_transform_visual_missile_periodic") { } + + class spell_transform_visual_missile_periodic_AuraScript : public AuraScript + { + PrepareAuraScript(spell_transform_visual_missile_periodic_AuraScript); + + void OnPeriodic(AuraEffect const* /*aurEff*/) + { + GetTarget()->CastSpell((Unit*)nullptr, RAND(TRANSFORM_VISUAL_MISSILE_1, TRANSFORM_VISUAL_MISSILE_2), true); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_transform_visual_missile_periodic_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_transform_visual_missile_periodic_AuraScript(); + } +}; + +class spell_summon_blood_elves_periodic : public SpellScriptLoader +{ + public: + spell_summon_blood_elves_periodic() : SpellScriptLoader("spell_summon_blood_elves_periodic") { } + + class spell_summon_blood_elves_periodic_AuraScript : public AuraScript + { + PrepareAuraScript(spell_summon_blood_elves_periodic_AuraScript); + + void OnPeriodic(AuraEffect const* /*aurEff*/) + { + GetTarget()->CastSpell((Unit*)nullptr, SPELL_SUMMON_BLOOD_ELVES_SCRIPT, true); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_summon_blood_elves_periodic_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_summon_blood_elves_periodic_AuraScript(); + } }; void AddSC_boss_muru() @@ -600,4 +736,9 @@ void AddSC_boss_muru() new npc_dark_fiend(); new npc_void_sentinel(); new npc_blackhole(); + new spell_summon_blood_elves_script(); + new spell_muru_darkness(); + new spell_dark_fiend_skin(); + new spell_transform_visual_missile_periodic(); + new spell_summon_blood_elves_periodic(); } diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h index c6b4ae753a5..7ea0fc4bc7d 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h @@ -97,7 +97,8 @@ enum CreatureIds NPC_FURY_MAGE = 25799, NPC_VOID_SENTINEL = 25772, NPC_VOID_SPAWN = 25824, - NPC_BLACK_HOLE = 25855 + NPC_BLACK_HOLE = 25855, + NPC_MURU_PORTAL_TARGET = 25770 }; enum GameObjectIds diff --git a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp index a5fed30a6c6..68391c65655 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp @@ -98,7 +98,7 @@ class boss_archaedas : public CreatureScript instance->SetData(0, 5); // respawn any dead minions me->setFaction(35); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->AddAura(SPELL_FREEZE_ANIM, me); } @@ -111,7 +111,7 @@ class boss_archaedas : public CreatureScript DoCast(minion, SPELL_AWAKEN_VAULT_WALKER, flag); minion->CastSpell(minion, SPELL_ARCHAEDAS_AWAKEN, true); minion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - minion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + minion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); minion->setFaction(14); minion->RemoveAura(SPELL_MINION_FREEZE_ANIM); } @@ -121,7 +121,7 @@ class boss_archaedas : public CreatureScript { me->setFaction(14); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); } void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override @@ -261,7 +261,7 @@ class npc_archaedas_minions : public CreatureScript me->setFaction(35); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->RemoveAllAuras(); me->AddAura(SPELL_MINION_FREEZE_ANIM, me); } @@ -271,7 +271,7 @@ class npc_archaedas_minions : public CreatureScript me->setFaction (14); me->RemoveAllAuras(); me->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); bAmIAwake = true; } @@ -350,7 +350,7 @@ class npc_stonekeepers : public CreatureScript { me->setFaction(35); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->RemoveAllAuras(); me->AddAura(SPELL_MINION_FREEZE_ANIM, me); } @@ -359,7 +359,7 @@ class npc_stonekeepers : public CreatureScript { me->setFaction(14); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); } void UpdateAI(uint32 /*diff*/) override diff --git a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp index 8c78fb7ff1b..28a3a4eb4e0 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp @@ -147,7 +147,7 @@ class instance_uldaman : public InstanceMapScript creature->setFaction(35); creature->RemoveAllAuras(); creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); creature->AddAura(SPELL_MINION_FREEZE_ANIM, creature); } @@ -178,7 +178,7 @@ class instance_uldaman : public InstanceMapScript Creature* target = instance->GetCreature(*i); if (!target || !target->IsAlive()) continue; - target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); target->setFaction(14); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); target->RemoveAura(SPELL_MINION_FREEZE_ANIM); @@ -202,7 +202,7 @@ class instance_uldaman : public InstanceMapScript Creature* target = instance->GetCreature(*i); if (!target || !target->IsAlive() || target->getFaction() == 14) continue; - target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); target->setFaction(14); target->RemoveAura(SPELL_MINION_FREEZE_ANIM); @@ -268,7 +268,7 @@ class instance_uldaman : public InstanceMapScript return; ironaya->setFaction(415); - ironaya->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + ironaya->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); ironaya->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); ironaya->GetMotionMaster()->Clear(); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp index 791f68bae31..72e76ba52bf 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp @@ -425,7 +425,7 @@ class npc_akilzon_eagle : public CreatureScript if (Unit* target = ObjectAccessor::GetUnit(*me, TargetGUID)) DoCast(target, SPELL_EAGLE_SWOOP, true); TargetGUID.Clear(); - me->SetSpeed(MOVE_RUN, 1.2f); + me->SetSpeedRate(MOVE_RUN, 1.2f); EagleSwoop_Timer = urand(5000, 10000); } } @@ -454,7 +454,7 @@ class npc_akilzon_eagle : public CreatureScript { target->GetContactPoint(me, x, y, z); z += 2; - me->SetSpeed(MOVE_RUN, 5.0f); + me->SetSpeedRate(MOVE_RUN, 5.0f); TargetGUID = target->GetGUID(); } me->GetMotionMaster()->MovePoint(0, x, y, z); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp index cc55f758a22..5ec57fc44b6 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp @@ -29,109 +29,104 @@ EndScriptData */ #include "SpellAuraEffects.h" #include "zulaman.h" -#define YELL_AGGRO "Da shadow gonna fall on you... " -#define SOUND_YELL_AGGRO 12041 -#define YELL_SPIRIT_BOLTS "Your soul gonna bleed!" -#define SOUND_YELL_SPIRIT_BOLTS 12047 -#define YELL_DRAIN_POWER "Darkness comin\' for you" -#define SOUND_YELL_DRAIN_POWER 12046 -#define YELL_KILL_ONE "Dis a nightmare ya don\' wake up from!" -#define SOUND_YELL_KILL_ONE 12043 -#define YELL_KILL_TWO "Azzaga choogo zinn!" -#define SOUND_YELL_KILL_TWO 12044 -#define YELL_DEATH "Dis not... da end of me..." -#define SOUND_YELL_DEATH 12051 - +enum Yells +{ + YELL_AGGRO = 0, + YELL_KILL_ONE = 1, + YELL_KILL_TWO = 2, + YELL_DRAIN_POWER = 3, + YELL_SPIRIT_BOLTS = 4, + YELL_DEATH = 5 +}; enum Creatures { - NPC_TEMP_TRIGGER = 23920 + NPC_TEMP_TRIGGER = 23920 }; enum Spells { - SPELL_SPIRIT_BOLTS = 43383, - SPELL_DRAIN_POWER = 44131, - SPELL_SIPHON_SOUL = 43501, + SPELL_SPIRIT_BOLTS = 43383, + SPELL_DRAIN_POWER = 44131, + SPELL_SIPHON_SOUL = 43501, // Druid - SPELL_DR_THORNS = 43420, - SPELL_DR_LIFEBLOOM = 43421, - SPELL_DR_MOONFIRE = 43545, + SPELL_DR_THORNS = 43420, + SPELL_DR_LIFEBLOOM = 43421, + SPELL_DR_MOONFIRE = 43545, // Hunter - SPELL_HU_EXPLOSIVE_TRAP = 43444, - SPELL_HU_FREEZING_TRAP = 43447, - SPELL_HU_SNAKE_TRAP = 43449, + SPELL_HU_EXPLOSIVE_TRAP = 43444, + SPELL_HU_FREEZING_TRAP = 43447, + SPELL_HU_SNAKE_TRAP = 43449, // Mage - SPELL_MG_FIREBALL = 41383, - SPELL_MG_FROST_NOVA = 43426, - SPELL_MG_ICE_LANCE = 43427, - SPELL_MG_FROSTBOLT = 43428, + SPELL_MG_FIREBALL = 41383, + SPELL_MG_FROST_NOVA = 43426, + SPELL_MG_ICE_LANCE = 43427, + SPELL_MG_FROSTBOLT = 43428, // Paladin - SPELL_PA_CONSECRATION = 43429, - SPELL_PA_AVENGING_WRATH = 43430, - SPELL_PA_HOLY_LIGHT = 43451, + SPELL_PA_CONSECRATION = 43429, + SPELL_PA_AVENGING_WRATH = 43430, + SPELL_PA_HOLY_LIGHT = 43451, // Priest - SPELL_PR_HEAL = 41372, - SPELL_PR_MIND_BLAST = 41374, - SPELL_PR_SW_DEATH = 41375, - SPELL_PR_PSYCHIC_SCREAM = 43432, - SPELL_PR_MIND_CONTROL = 43550, - SPELL_PR_PAIN_SUPP = 44416, + SPELL_PR_HEAL = 41372, + SPELL_PR_MIND_BLAST = 41374, + SPELL_PR_SW_DEATH = 41375, + SPELL_PR_PSYCHIC_SCREAM = 43432, + SPELL_PR_MIND_CONTROL = 43550, + SPELL_PR_PAIN_SUPP = 44416, // Rogue - SPELL_RO_BLIND = 43433, - SPELL_RO_SLICE_DICE = 43457, - SPELL_RO_WOUND_POISON = 43461, + SPELL_RO_BLIND = 43433, + SPELL_RO_SLICE_DICE = 43457, + SPELL_RO_WOUND_POISON = 43461, // Shaman - SPELL_SH_CHAIN_LIGHT = 43435, - SPELL_SH_FIRE_NOVA = 43436, - SPELL_SH_HEALING_WAVE = 43548, + SPELL_SH_CHAIN_LIGHT = 43435, + SPELL_SH_FIRE_NOVA = 43436, + SPELL_SH_HEALING_WAVE = 43548, // Warlock - SPELL_WL_CURSE_OF_DOOM = 43439, - SPELL_WL_RAIN_OF_FIRE = 43440, - SPELL_WL_UNSTABLE_AFFL = 43522, - SPELL_WL_UNSTABLE_AFFL_DISPEL = 43523, + SPELL_WL_CURSE_OF_DOOM = 43439, + SPELL_WL_RAIN_OF_FIRE = 43440, + SPELL_WL_UNSTABLE_AFFL = 43522, + SPELL_WL_UNSTABLE_AFFL_DISPEL = 43523, // Warrior - SPELL_WR_MORTAL_STRIKE = 43441, - SPELL_WR_WHIRLWIND = 43442, - SPELL_WR_SPELL_REFLECT = 43443, + SPELL_WR_MORTAL_STRIKE = 43441, + SPELL_WR_WHIRLWIND = 43442, + SPELL_WR_SPELL_REFLECT = 43443, // Thurg - SPELL_BLOODLUST = 43578, - SPELL_CLEAVE = 15496, + SPELL_BLOODLUST = 43578, + SPELL_CLEAVE = 15496, // Gazakroth - SPELL_FIREBOLT = 43584, + SPELL_FIREBOLT = 43584, // Alyson Antille - SPELL_FLASH_HEAL = 43575, - SPELL_DISPEL_MAGIC = 43577, + SPELL_FLASH_HEAL = 43575, + SPELL_DISPEL_MAGIC = 43577, // Lord Raadan - SPELL_FLAME_BREATH = 43582, - SPELL_THUNDERCLAP = 43583, + SPELL_FLAME_BREATH = 43582, + SPELL_THUNDERCLAP = 43583, // Darkheart - SPELL_PSYCHIC_WAIL = 43590, + SPELL_PSYCHIC_WAIL = 43590, // Slither - SPELL_VENOM_SPIT = 43579, + SPELL_VENOM_SPIT = 43579, // Fenstalker - SPELL_VOLATILE_INFECTION = 43586, + SPELL_VOLATILE_INFECTION = 43586, // Koragg - SPELL_COLD_STARE = 43593, - SPELL_MIGHTY_BLOW = 43592 - + SPELL_COLD_STARE = 43593, + SPELL_MIGHTY_BLOW = 43592 }; #define ORIENT 1.5696f @@ -306,8 +301,7 @@ class boss_hexlord_malacrass : public CreatureScript instance->SetData(DATA_HEXLORDEVENT, IN_PROGRESS); DoZoneInCombat(); - me->Yell(YELL_AGGRO, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_AGGRO); + Talk(YELL_AGGRO); for (uint8 i = 0; i < 4; ++i) { @@ -327,12 +321,10 @@ class boss_hexlord_malacrass : public CreatureScript switch (urand(0, 1)) { case 0: - me->Yell(YELL_KILL_ONE, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_KILL_ONE); + Talk(YELL_KILL_ONE); break; case 1: - me->Yell(YELL_KILL_TWO, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_KILL_TWO); + Talk(YELL_KILL_TWO); break; } } @@ -341,8 +333,7 @@ class boss_hexlord_malacrass : public CreatureScript { instance->SetData(DATA_HEXLORDEVENT, DONE); - me->Yell(YELL_DEATH, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_DEATH); + Talk(YELL_DEATH); for (uint8 i = 0; i < 4; ++i) { @@ -415,8 +406,7 @@ class boss_hexlord_malacrass : public CreatureScript if (DrainPower_Timer <= diff) { DoCast(me, SPELL_DRAIN_POWER, true); - me->Yell(YELL_DRAIN_POWER, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_DRAIN_POWER); + Talk(YELL_DRAIN_POWER); DrainPower_Timer = urand(40000, 55000); // must cast in 60 sec, or buff/debuff will disappear } else DrainPower_Timer -= diff; @@ -427,8 +417,7 @@ class boss_hexlord_malacrass : public CreatureScript else { DoCast(me, SPELL_SPIRIT_BOLTS, false); - me->Yell(YELL_SPIRIT_BOLTS, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_SPIRIT_BOLTS); + Talk(YELL_SPIRIT_BOLTS); SpiritBolts_Timer = 40000; SiphonSoul_Timer = 10000; // ready to drain PlayerAbility_Timer = 99999; diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp index 37505a8b74d..188f9d0cc03 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp @@ -30,21 +30,41 @@ EndScriptData */ #include "GridNotifiersImpl.h" #include "CellImpl.h" -enum Spells +enum Yells { - SPELL_BERSERK = 45078, + YELL_NALORAKK_WAVE1 = 0, + YELL_NALORAKK_WAVE2 = 1, + YELL_NALORAKK_WAVE3 = 2, + YELL_NALORAKK_WAVE4 = 3, + YELL_AGGRO = 4, + YELL_SURGE = 5, + YELL_SHIFTEDTOBEAR = 6, + YELL_SHIFTEDTOTROLL = 7, + YELL_BERSERK = 8, + YELL_KILL_ONE = 9, + YELL_KILL_TWO = 10, + YELL_DEATH = 11 + +// Not yet implemented +// YELL_NALORAKK_EVENT1 = 12, +// YELL_NALORAKK_EVENT2 = 13 +}; +enum Spells +{ // Troll form - SPELL_BRUTALSWIPE = 42384, - SPELL_MANGLE = 42389, - SPELL_MANGLEEFFECT = 44955, - SPELL_SURGE = 42402, - SPELL_BEARFORM = 42377, + SPELL_BRUTALSWIPE = 42384, + SPELL_MANGLE = 42389, + SPELL_MANGLEEFFECT = 44955, + SPELL_SURGE = 42402, + SPELL_BEARFORM = 42377, // Bear form - SPELL_LACERATINGSLASH = 42395, - SPELL_RENDFLESH = 42397, - SPELL_DEAFENINGROAR = 42398 + SPELL_LACERATINGSLASH = 42395, + SPELL_RENDFLESH = 42397, + SPELL_DEAFENINGROAR = 42398, + + SPELL_BERSERK = 45078 }; // Trash Waves @@ -57,45 +77,9 @@ float NalorakkWay[8][3] = {-79.929f, 1395.958f, 27.31f}, {-80.072f, 1374.555f, 40.87f}, // waypoint 3 {-80.072f, 1314.398f, 40.87f}, - {-80.072f, 1295.775f, 48.60f} // waypoint 4 + {-80.072f, 1295.775f, 48.60f} // waypoint 4 }; -#define YELL_NALORAKK_WAVE1 "Get da move on, guards! It be killin' time!" -#define SOUND_NALORAKK_WAVE1 12066 -#define YELL_NALORAKK_WAVE2 "Guards, go already! Who you more afraid of, dem... or me?" -#define SOUND_NALORAKK_WAVE2 12067 -#define YELL_NALORAKK_WAVE3 "Ride now! Ride out dere and bring me back some heads!" -#define SOUND_NALORAKK_WAVE3 12068 -#define YELL_NALORAKK_WAVE4 "I be losin' me patience! Go on: make dem wish dey was never born!" -#define SOUND_NALORAKK_WAVE4 12069 - -//Unimplemented SoundIDs -/* -#define SOUND_NALORAKK_EVENT1 12078 -#define SOUND_NALORAKK_EVENT2 12079 -*/ - -//General defines -#define YELL_AGGRO "You be dead soon enough!" -#define SOUND_YELL_AGGRO 12070 -#define YELL_KILL_ONE "Mua-ha-ha! Now whatchoo got to say?" -#define SOUND_YELL_KILL_ONE 12075 -#define YELL_KILL_TWO "Da Amani gonna rule again!" -#define SOUND_YELL_KILL_TWO 12076 -#define YELL_DEATH "I... be waitin' on da udda side...." -#define SOUND_YELL_DEATH 12077 -#define YELL_BERSERK "You had your chance, now it be too late!" //Never seen this being used, so just guessing from what I hear. -#define SOUND_YELL_BERSERK 12074 -#define YELL_SURGE "I bring da pain!" -#define SOUND_YELL_SURGE 12071 - -#define YELL_SHIFTEDTOTROLL "Make way for Nalorakk!" -#define SOUND_YELL_TOTROLL 12073 - - -#define YELL_SHIFTEDTOBEAR "You call on da beast, you gonna get more dan you bargain for!" -#define SOUND_YELL_TOBEAR 12072 - class boss_nalorakk : public CreatureScript { public: @@ -158,7 +142,7 @@ class boss_nalorakk : public CreatureScript me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); inMove = false; waitTimer = 0; - me->SetSpeed(MOVE_RUN, 2); + me->SetSpeedRate(MOVE_RUN, 2); me->SetWalk(false); }else { @@ -227,8 +211,7 @@ class boss_nalorakk : public CreatureScript case 0: if (me->IsWithinDistInMap(who, 50)) { - me->Yell(YELL_NALORAKK_WAVE1, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_NALORAKK_WAVE1); + Talk(YELL_NALORAKK_WAVE1); (*me).GetMotionMaster()->MovePoint(1, NalorakkWay[1][0], NalorakkWay[1][1], NalorakkWay[1][2]); MovePhase ++; @@ -240,8 +223,7 @@ class boss_nalorakk : public CreatureScript case 2: if (me->IsWithinDistInMap(who, 40)) { - me->Yell(YELL_NALORAKK_WAVE2, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_NALORAKK_WAVE2); + Talk(YELL_NALORAKK_WAVE2); (*me).GetMotionMaster()->MovePoint(3, NalorakkWay[3][0], NalorakkWay[3][1], NalorakkWay[3][2]); MovePhase ++; @@ -253,8 +235,7 @@ class boss_nalorakk : public CreatureScript case 5: if (me->IsWithinDistInMap(who, 40)) { - me->Yell(YELL_NALORAKK_WAVE3, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_NALORAKK_WAVE3); + Talk(YELL_NALORAKK_WAVE3); (*me).GetMotionMaster()->MovePoint(6, NalorakkWay[6][0], NalorakkWay[6][1], NalorakkWay[6][2]); MovePhase ++; @@ -268,8 +249,7 @@ class boss_nalorakk : public CreatureScript { SendAttacker(who); - me->Yell(YELL_NALORAKK_WAVE4, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_NALORAKK_WAVE4); + Talk(YELL_NALORAKK_WAVE4); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); @@ -287,8 +267,7 @@ class boss_nalorakk : public CreatureScript { instance->SetData(DATA_NALORAKKEVENT, IN_PROGRESS); - me->Yell(YELL_AGGRO, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_AGGRO); + Talk(YELL_AGGRO); DoZoneInCombat(); } @@ -296,8 +275,7 @@ class boss_nalorakk : public CreatureScript { instance->SetData(DATA_NALORAKKEVENT, DONE); - me->Yell(YELL_DEATH, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_DEATH); + Talk(YELL_DEATH); } void KilledUnit(Unit* /*victim*/) override @@ -305,12 +283,10 @@ class boss_nalorakk : public CreatureScript switch (urand(0, 1)) { case 0: - me->Yell(YELL_KILL_ONE, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_KILL_ONE); + Talk(YELL_KILL_ONE); break; case 1: - me->Yell(YELL_KILL_TWO, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_KILL_TWO); + Talk(YELL_KILL_TWO); break; } } @@ -373,8 +349,7 @@ class boss_nalorakk : public CreatureScript if (Berserk_Timer <= diff) { DoCast(me, SPELL_BERSERK, true); - me->Yell(YELL_BERSERK, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_BERSERK); + Talk(YELL_BERSERK); Berserk_Timer = 600000; } else Berserk_Timer -= diff; @@ -383,8 +358,7 @@ class boss_nalorakk : public CreatureScript if (inBearForm) { // me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, 5122); - me->Yell(YELL_SHIFTEDTOTROLL, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_TOTROLL); + Talk(YELL_SHIFTEDTOTROLL); me->RemoveAurasDueToSpell(SPELL_BEARFORM); Surge_Timer = urand(15000, 20000); BrutalSwipe_Timer = urand(7000, 12000); @@ -395,8 +369,7 @@ class boss_nalorakk : public CreatureScript else { // me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, 0); - me->Yell(YELL_SHIFTEDTOBEAR, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_TOBEAR); + Talk(YELL_SHIFTEDTOBEAR); DoCast(me, SPELL_BEARFORM, true); LaceratingSlash_Timer = 2000; // dur 18s RendFlesh_Timer = 3000; // dur 5s @@ -426,8 +399,7 @@ class boss_nalorakk : public CreatureScript if (Surge_Timer <= diff) { - me->Yell(YELL_SURGE, LANG_UNIVERSAL); - DoPlaySoundToSet(me, SOUND_YELL_SURGE); + Talk(YELL_SURGE); Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 45, true); if (target) DoCast(target, SPELL_SURGE); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp index 96c0798ae05..a1c2369cf66 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp @@ -347,7 +347,7 @@ class boss_zuljin : public CreatureScript Vortex->CastSpell(Vortex, SPELL_CYCLONE_PASSIVE, true); Vortex->CastSpell(Vortex, SPELL_CYCLONE_VISUAL, true); Vortex->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - Vortex->SetSpeed(MOVE_RUN, 1.0f); + Vortex->SetSpeedRate(MOVE_RUN, 1.0f); Vortex->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM, 0)); DoZoneInCombat(Vortex); } @@ -438,7 +438,7 @@ class boss_zuljin : public CreatureScript { if (me->GetVictim()) TankGUID = me->EnsureVictim()->GetGUID(); - me->SetSpeed(MOVE_RUN, 5.0f); + me->SetSpeedRate(MOVE_RUN, 5.0f); AttackStart(target); // change victim Claw_Rage_Timer = 0; Claw_Loop_Timer = 500; @@ -462,7 +462,7 @@ class boss_zuljin : public CreatureScript if (Claw_Counter == 12) { Claw_Rage_Timer = urand(15000, 20000); - me->SetSpeed(MOVE_RUN, 1.2f); + me->SetSpeedRate(MOVE_RUN, 1.2f); AttackStart(ObjectAccessor::GetUnit(*me, TankGUID)); TankGUID.Clear(); return; @@ -487,7 +487,7 @@ class boss_zuljin : public CreatureScript if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { TankGUID = me->EnsureVictim()->GetGUID(); - me->SetSpeed(MOVE_RUN, 5.0f); + me->SetSpeedRate(MOVE_RUN, 5.0f); AttackStart(target); // change victim Lynx_Rush_Timer = 0; Claw_Counter = 0; @@ -510,7 +510,7 @@ class boss_zuljin : public CreatureScript if (Claw_Counter == 9) { Lynx_Rush_Timer = urand(15000, 20000); - me->SetSpeed(MOVE_RUN, 1.2f); + me->SetSpeedRate(MOVE_RUN, 1.2f); AttackStart(ObjectAccessor::GetUnit(*me, TankGUID)); TankGUID.Clear(); } diff --git a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp index 972acdc3f9f..9b668169dca 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp @@ -162,7 +162,7 @@ class npc_zulaman_hostage : public CreatureScript { if (HostageEntry[i] == entry) { - creature->SummonGameObject(ChestEntry[i], x-2, y, z, 0, 0, 0, 0, 0, 0); + creature->SummonGameObject(ChestEntry[i], Position(x - 2, y, z, 0.f), G3D::Quat(), 0); break; } } diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp index 8c179af2adf..3697b0876c8 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp @@ -148,6 +148,11 @@ class boss_mandokir : public CreatureScript instance->SaveToDB(); } + void JustReachedHome() override + { + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + } + void EnterCombat(Unit* /*who*/) override { _EnterCombat(); @@ -194,9 +199,9 @@ class boss_mandokir : public CreatureScript me->SetWalk(false); if (id == POINT_MANDOKIR_END) { - me->SetHomePosition(PosMandokir[0]); + me->SetHomePosition(PosMandokir[1]); + me->GetMotionMaster()->MoveTargetedHome(); instance->SetBossState(DATA_MANDOKIR, NOT_STARTED); - me->DespawnOrUnsummon(6000); // No idea how to respawn on wipe. } } } diff --git a/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp b/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp new file mode 100644 index 00000000000..adcb4f9fc9a --- /dev/null +++ b/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp @@ -0,0 +1,368 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_alterac_valley(); //Alterac Valley +void AddSC_boss_balinda(); +void AddSC_boss_drekthar(); +void AddSC_boss_galvangar(); +void AddSC_boss_vanndar(); +void AddSC_blackrock_depths(); //Blackrock Depths +void AddSC_boss_ambassador_flamelash(); +void AddSC_boss_draganthaurissan(); +void AddSC_boss_general_angerforge(); +void AddSC_boss_high_interrogator_gerstahn(); +void AddSC_boss_magmus(); +void AddSC_boss_moira_bronzebeard(); +void AddSC_boss_tomb_of_seven(); +void AddSC_instance_blackrock_depths(); +void AddSC_boss_drakkisath(); //Blackrock Spire +void AddSC_boss_halycon(); +void AddSC_boss_highlordomokk(); +void AddSC_boss_mothersmolderweb(); +void AddSC_boss_overlordwyrmthalak(); +void AddSC_boss_shadowvosh(); +void AddSC_boss_thebeast(); +void AddSC_boss_warmastervoone(); +void AddSC_boss_quatermasterzigris(); +void AddSC_boss_pyroguard_emberseer(); +void AddSC_boss_gyth(); +void AddSC_boss_rend_blackhand(); +void AddSC_boss_gizrul_the_slavener(); +void AddSC_boss_urok_doomhowl(); +void AddSC_boss_lord_valthalak(); +void AddSC_instance_blackrock_spire(); +void AddSC_boss_razorgore(); //Blackwing lair +void AddSC_boss_vaelastrasz(); +void AddSC_boss_broodlord(); +void AddSC_boss_firemaw(); +void AddSC_boss_ebonroc(); +void AddSC_boss_flamegor(); +void AddSC_boss_chromaggus(); +void AddSC_boss_nefarian(); +void AddSC_instance_blackwing_lair(); +void AddSC_deadmines(); //Deadmines +void AddSC_instance_deadmines(); +void AddSC_boss_mr_smite(); +void AddSC_gnomeregan(); //Gnomeregan +void AddSC_instance_gnomeregan(); +void AddSC_boss_attumen(); //Karazhan +void AddSC_boss_curator(); +void AddSC_boss_maiden_of_virtue(); +void AddSC_boss_shade_of_aran(); +void AddSC_boss_malchezaar(); +void AddSC_boss_terestian_illhoof(); +void AddSC_boss_moroes(); +void AddSC_bosses_opera(); +void AddSC_boss_netherspite(); +void AddSC_instance_karazhan(); +void AddSC_karazhan(); +void AddSC_boss_nightbane(); +void AddSC_boss_felblood_kaelthas(); // Magister's Terrace +void AddSC_boss_selin_fireheart(); +void AddSC_boss_vexallus(); +void AddSC_boss_priestess_delrissa(); +void AddSC_instance_magisters_terrace(); +void AddSC_magisters_terrace(); +void AddSC_boss_lucifron(); //Molten core +void AddSC_boss_magmadar(); +void AddSC_boss_gehennas(); +void AddSC_boss_garr(); +void AddSC_boss_baron_geddon(); +void AddSC_boss_shazzrah(); +void AddSC_boss_golemagg(); +void AddSC_boss_sulfuron(); +void AddSC_boss_majordomo(); +void AddSC_boss_ragnaros(); +void AddSC_instance_molten_core(); +void AddSC_the_scarlet_enclave(); //Scarlet Enclave +void AddSC_the_scarlet_enclave_c1(); +void AddSC_the_scarlet_enclave_c2(); +void AddSC_the_scarlet_enclave_c5(); +void AddSC_boss_arcanist_doan(); //Scarlet Monastery +void AddSC_boss_azshir_the_sleepless(); +void AddSC_boss_bloodmage_thalnos(); +void AddSC_boss_headless_horseman(); +void AddSC_boss_herod(); +void AddSC_boss_high_inquisitor_fairbanks(); +void AddSC_boss_houndmaster_loksey(); +void AddSC_boss_interrogator_vishas(); +void AddSC_boss_scorn(); +void AddSC_instance_scarlet_monastery(); +void AddSC_boss_mograine_and_whitemane(); +void AddSC_boss_darkmaster_gandling(); //Scholomance +void AddSC_boss_death_knight_darkreaver(); +void AddSC_boss_theolenkrastinov(); +void AddSC_boss_illuciabarov(); +void AddSC_boss_instructormalicia(); +void AddSC_boss_jandicebarov(); +void AddSC_boss_kormok(); +void AddSC_boss_lordalexeibarov(); +void AddSC_boss_lorekeeperpolkelt(); +void AddSC_boss_rasfrost(); +void AddSC_boss_theravenian(); +void AddSC_boss_vectus(); +void AddSC_boss_kirtonos_the_herald(); +void AddSC_instance_scholomance(); +void AddSC_shadowfang_keep(); //Shadowfang keep +void AddSC_instance_shadowfang_keep(); +void AddSC_boss_magistrate_barthilas(); //Stratholme +void AddSC_boss_maleki_the_pallid(); +void AddSC_boss_nerubenkan(); +void AddSC_boss_cannon_master_willey(); +void AddSC_boss_baroness_anastari(); +void AddSC_boss_ramstein_the_gorger(); +void AddSC_boss_timmy_the_cruel(); +void AddSC_boss_postmaster_malown(); +void AddSC_boss_baron_rivendare(); +void AddSC_boss_dathrohan_balnazzar(); +void AddSC_boss_order_of_silver_hand(); +void AddSC_instance_stratholme(); +void AddSC_stratholme(); +void AddSC_sunken_temple(); // Sunken Temple +void AddSC_instance_sunken_temple(); +void AddSC_instance_sunwell_plateau(); //Sunwell Plateau +void AddSC_boss_kalecgos(); +void AddSC_boss_brutallus(); +void AddSC_boss_felmyst(); +void AddSC_boss_eredar_twins(); +void AddSC_boss_muru(); +void AddSC_boss_kiljaeden(); +void AddSC_sunwell_plateau(); +void AddSC_boss_archaedas(); //Uldaman +void AddSC_boss_ironaya(); +void AddSC_uldaman(); +void AddSC_instance_uldaman(); +void AddSC_instance_the_stockade(); //The Stockade +void AddSC_boss_akilzon(); //Zul'Aman +void AddSC_boss_halazzi(); +void AddSC_boss_hex_lord_malacrass(); +void AddSC_boss_janalai(); +void AddSC_boss_nalorakk(); +void AddSC_boss_zuljin(); +void AddSC_instance_zulaman(); +void AddSC_zulaman(); +void AddSC_boss_jeklik(); //Zul'Gurub +void AddSC_boss_venoxis(); +void AddSC_boss_marli(); +void AddSC_boss_mandokir(); +void AddSC_boss_gahzranka(); +void AddSC_boss_thekal(); +void AddSC_boss_arlokk(); +void AddSC_boss_jindo(); +void AddSC_boss_hakkar(); +void AddSC_boss_grilek(); +void AddSC_boss_hazzarah(); +void AddSC_boss_renataki(); +void AddSC_boss_wushoolay(); +void AddSC_instance_zulgurub(); +//void AddSC_alterac_mountains(); +void AddSC_arathi_highlands(); +void AddSC_blasted_lands(); +void AddSC_burning_steppes(); +void AddSC_duskwood(); +void AddSC_eastern_plaguelands(); +void AddSC_ghostlands(); +void AddSC_hinterlands(); +void AddSC_isle_of_queldanas(); +void AddSC_redridge_mountains(); +void AddSC_silverpine_forest(); +void AddSC_stormwind_city(); +void AddSC_stranglethorn_vale(); +void AddSC_swamp_of_sorrows(); +void AddSC_tirisfal_glades(); +void AddSC_undercity(); +void AddSC_western_plaguelands(); +void AddSC_wetlands(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddEasternKingdomsScripts() +{ + AddSC_alterac_valley(); //Alterac Valley + AddSC_boss_balinda(); + AddSC_boss_drekthar(); + AddSC_boss_galvangar(); + AddSC_boss_vanndar(); + AddSC_blackrock_depths(); //Blackrock Depths + AddSC_boss_ambassador_flamelash(); + AddSC_boss_draganthaurissan(); + AddSC_boss_general_angerforge(); + AddSC_boss_high_interrogator_gerstahn(); + AddSC_boss_magmus(); + AddSC_boss_moira_bronzebeard(); + AddSC_boss_tomb_of_seven(); + AddSC_instance_blackrock_depths(); + AddSC_boss_drakkisath(); //Blackrock Spire + AddSC_boss_halycon(); + AddSC_boss_highlordomokk(); + AddSC_boss_mothersmolderweb(); + AddSC_boss_overlordwyrmthalak(); + AddSC_boss_shadowvosh(); + AddSC_boss_thebeast(); + AddSC_boss_warmastervoone(); + AddSC_boss_quatermasterzigris(); + AddSC_boss_pyroguard_emberseer(); + AddSC_boss_gyth(); + AddSC_boss_rend_blackhand(); + AddSC_boss_gizrul_the_slavener(); + AddSC_boss_urok_doomhowl(); + AddSC_boss_lord_valthalak(); + AddSC_instance_blackrock_spire(); + AddSC_boss_razorgore(); //Blackwing lair + AddSC_boss_vaelastrasz(); + AddSC_boss_broodlord(); + AddSC_boss_firemaw(); + AddSC_boss_ebonroc(); + AddSC_boss_flamegor(); + AddSC_boss_chromaggus(); + AddSC_boss_nefarian(); + AddSC_instance_blackwing_lair(); + AddSC_deadmines(); //Deadmines + AddSC_boss_mr_smite(); + AddSC_instance_deadmines(); + AddSC_gnomeregan(); //Gnomeregan + AddSC_instance_gnomeregan(); + AddSC_boss_attumen(); //Karazhan + AddSC_boss_curator(); + AddSC_boss_maiden_of_virtue(); + AddSC_boss_shade_of_aran(); + AddSC_boss_malchezaar(); + AddSC_boss_terestian_illhoof(); + AddSC_boss_moroes(); + AddSC_bosses_opera(); + AddSC_boss_netherspite(); + AddSC_instance_karazhan(); + AddSC_karazhan(); + AddSC_boss_nightbane(); + AddSC_boss_felblood_kaelthas(); // Magister's Terrace + AddSC_boss_selin_fireheart(); + AddSC_boss_vexallus(); + AddSC_boss_priestess_delrissa(); + AddSC_instance_magisters_terrace(); + AddSC_magisters_terrace(); + AddSC_boss_lucifron(); //Molten core + AddSC_boss_magmadar(); + AddSC_boss_gehennas(); + AddSC_boss_garr(); + AddSC_boss_baron_geddon(); + AddSC_boss_shazzrah(); + AddSC_boss_golemagg(); + AddSC_boss_sulfuron(); + AddSC_boss_majordomo(); + AddSC_boss_ragnaros(); + AddSC_instance_molten_core(); + AddSC_the_scarlet_enclave(); //Scarlet Enclave + AddSC_the_scarlet_enclave_c1(); + AddSC_the_scarlet_enclave_c2(); + AddSC_the_scarlet_enclave_c5(); + AddSC_boss_arcanist_doan(); //Scarlet Monastery + AddSC_boss_azshir_the_sleepless(); + AddSC_boss_bloodmage_thalnos(); + AddSC_boss_headless_horseman(); + AddSC_boss_herod(); + AddSC_boss_high_inquisitor_fairbanks(); + AddSC_boss_houndmaster_loksey(); + AddSC_boss_interrogator_vishas(); + AddSC_boss_scorn(); + AddSC_instance_scarlet_monastery(); + AddSC_boss_mograine_and_whitemane(); + AddSC_boss_darkmaster_gandling(); //Scholomance + AddSC_boss_death_knight_darkreaver(); + AddSC_boss_theolenkrastinov(); + AddSC_boss_illuciabarov(); + AddSC_boss_instructormalicia(); + AddSC_boss_jandicebarov(); + AddSC_boss_kormok(); + AddSC_boss_lordalexeibarov(); + AddSC_boss_lorekeeperpolkelt(); + AddSC_boss_rasfrost(); + AddSC_boss_theravenian(); + AddSC_boss_vectus(); + AddSC_boss_kirtonos_the_herald(); + AddSC_instance_scholomance(); + AddSC_shadowfang_keep(); //Shadowfang keep + AddSC_instance_shadowfang_keep(); + AddSC_boss_magistrate_barthilas(); //Stratholme + AddSC_boss_maleki_the_pallid(); + AddSC_boss_nerubenkan(); + AddSC_boss_cannon_master_willey(); + AddSC_boss_baroness_anastari(); + AddSC_boss_ramstein_the_gorger(); + AddSC_boss_timmy_the_cruel(); + AddSC_boss_postmaster_malown(); + AddSC_boss_baron_rivendare(); + AddSC_boss_dathrohan_balnazzar(); + AddSC_boss_order_of_silver_hand(); + AddSC_instance_stratholme(); + AddSC_stratholme(); + AddSC_sunken_temple(); // Sunken Temple + AddSC_instance_sunken_temple(); + AddSC_instance_sunwell_plateau(); //Sunwell Plateau + AddSC_boss_kalecgos(); + AddSC_boss_brutallus(); + AddSC_boss_felmyst(); + AddSC_boss_eredar_twins(); + AddSC_boss_muru(); + AddSC_boss_kiljaeden(); + AddSC_sunwell_plateau(); + AddSC_instance_the_stockade(); //The Stockade + AddSC_boss_archaedas(); //Uldaman + AddSC_boss_ironaya(); + AddSC_uldaman(); + AddSC_instance_uldaman(); + AddSC_boss_akilzon(); //Zul'Aman + AddSC_boss_halazzi(); + AddSC_boss_hex_lord_malacrass(); + AddSC_boss_janalai(); + AddSC_boss_nalorakk(); + AddSC_boss_zuljin(); + AddSC_instance_zulaman(); + AddSC_zulaman(); + AddSC_boss_jeklik(); //Zul'Gurub + AddSC_boss_venoxis(); + AddSC_boss_marli(); + AddSC_boss_mandokir(); + AddSC_boss_gahzranka(); + AddSC_boss_thekal(); + AddSC_boss_arlokk(); + AddSC_boss_jindo(); + AddSC_boss_hakkar(); + AddSC_boss_grilek(); + AddSC_boss_hazzarah(); + AddSC_boss_renataki(); + AddSC_boss_wushoolay(); + AddSC_instance_zulgurub(); + //AddSC_alterac_mountains(); + AddSC_arathi_highlands(); + AddSC_blasted_lands(); + AddSC_burning_steppes(); + AddSC_duskwood(); + AddSC_eastern_plaguelands(); + AddSC_ghostlands(); + AddSC_hinterlands(); + AddSC_isle_of_queldanas(); + AddSC_redridge_mountains(); + AddSC_silverpine_forest(); + AddSC_stormwind_city(); + AddSC_stranglethorn_vale(); + AddSC_swamp_of_sorrows(); + AddSC_tirisfal_glades(); + AddSC_undercity(); + AddSC_western_plaguelands(); + AddSC_wetlands(); +} diff --git a/src/server/scripts/EasternKingdoms/zone_burning_steppes.cpp b/src/server/scripts/EasternKingdoms/zone_burning_steppes.cpp index df61a010f84..73b397553a5 100644 --- a/src/server/scripts/EasternKingdoms/zone_burning_steppes.cpp +++ b/src/server/scripts/EasternKingdoms/zone_burning_steppes.cpp @@ -19,7 +19,7 @@ /* ScriptData SDName: Burning_Steppes SD%Complete: 100 -SDComment: Quest support: 4224, 4866 +SDComment: Quest support: 4866 SDCategory: Burning Steppes EndScriptData */ @@ -36,25 +36,11 @@ EndContentData */ ## npc_ragged_john ######*/ -#define GOSSIP_HELLO "Official buisness, John. I need some information about Marsha Windsor. Tell me about the last time you saw him." -#define GOSSIP_SELECT1 "So what did you do?" -#define GOSSIP_SELECT2 "Start making sense, dwarf. I don't want to have anything to do with your cracker, your pappy, or any sort of 'discreditin'." -#define GOSSIP_SELECT3 "Ironfoe?" -#define GOSSIP_SELECT4 "Interesting... continue John." -#define GOSSIP_SELECT5 "So that's how Windsor died..." -#define GOSSIP_SELECT6 "So how did he die?" -#define GOSSIP_SELECT7 "Ok so where the hell is he? Wait a minute! Are you drunk?" -#define GOSSIP_SELECT8 "WHY is he in Blackrock Depths?" -#define GOSSIP_SELECT9 "300? So the Dark Irons killed him and dragged him into the Depths?" -#define GOSSIP_SELECT10 "Ahh... Ironfoe" -#define GOSSIP_SELECT11 "Thanks, Ragged John. Your story was very uplifting and informative" - enum RaggedJohn { - QUEST_THE_TRUE_MASTERS = 4224, - QUEST_MOTHERS_MILK = 4866, - SPELL_MOTHERS_MILK = 16468, - SPELL_WICKED_MILKING = 16472 + QUEST_MOTHERS_MILK = 4866, + SPELL_MOTHERS_MILK = 16468, + SPELL_WICKED_MILKING = 16472 }; class npc_ragged_john : public CreatureScript @@ -86,72 +72,13 @@ public: void EnterCombat(Unit* /*who*/) override { } }; - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->SEND_GOSSIP_MENU(2714, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->SEND_GOSSIP_MENU(2715, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->SEND_GOSSIP_MENU(2716, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - player->SEND_GOSSIP_MENU(2717, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); - player->SEND_GOSSIP_MENU(2718, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); - player->SEND_GOSSIP_MENU(2719, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+6: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT7, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); - player->SEND_GOSSIP_MENU(2720, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+7: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT8, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8); - player->SEND_GOSSIP_MENU(2721, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+8: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT9, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9); - player->SEND_GOSSIP_MENU(2722, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+9: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT10, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 10); - player->SEND_GOSSIP_MENU(2723, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+10: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT11, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); - player->SEND_GOSSIP_MENU(2725, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+11: - player->CLOSE_GOSSIP_MENU(); - player->AreaExploredOrEventHappens(QUEST_THE_TRUE_MASTERS); - break; - } - return true; - } - bool OnGossipHello(Player* player, Creature* creature) override { if (creature->IsQuestGiver()) + { player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_THE_TRUE_MASTERS) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - - player->SEND_GOSSIP_MENU(2713, creature->GetGUID()); + player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); + } return true; } diff --git a/src/server/scripts/EasternKingdoms/zone_eastern_plaguelands.cpp b/src/server/scripts/EasternKingdoms/zone_eastern_plaguelands.cpp index ce0ebf4d129..4cc72715868 100644 --- a/src/server/scripts/EasternKingdoms/zone_eastern_plaguelands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_eastern_plaguelands.cpp @@ -19,7 +19,7 @@ /* ScriptData SDName: Eastern_Plaguelands SD%Complete: 100 -SDComment: Quest support: 5211, 5742. Special vendor Augustus the Touched +SDComment: Quest support: 5211. Special vendor Augustus the Touched SDCategory: Eastern Plaguelands EndScriptData */ @@ -27,7 +27,6 @@ EndScriptData */ npc_ghoul_flayer npc_augustus_the_touched npc_darrowshire_spirit -npc_tirion_fordring EndContentData */ #include "ScriptMgr.h" @@ -133,63 +132,9 @@ public: }; }; -/*###### -## npc_tirion_fordring -######*/ - -#define GOSSIP_HELLO "I am ready to hear your tale, Tirion." -#define GOSSIP_SELECT1 "Thank you, Tirion. What of your identity?" -#define GOSSIP_SELECT2 "That is terrible." -#define GOSSIP_SELECT3 "I will, Tirion." - -class npc_tirion_fordring : public CreatureScript -{ -public: - npc_tirion_fordring() : CreatureScript("npc_tirion_fordring") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->SEND_GOSSIP_MENU(4493, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->SEND_GOSSIP_MENU(4494, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - player->SEND_GOSSIP_MENU(4495, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->CLOSE_GOSSIP_MENU(); - player->AreaExploredOrEventHappens(5742); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(5742) == QUEST_STATUS_INCOMPLETE && player->getStandState() == UNIT_STAND_STATE_SIT) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - void AddSC_eastern_plaguelands() { new npc_ghoul_flayer(); new npc_augustus_the_touched(); new npc_darrowshire_spirit(); - new npc_tirion_fordring(); } diff --git a/src/server/scripts/EasternKingdoms/zone_loch_modan.cpp b/src/server/scripts/EasternKingdoms/zone_loch_modan.cpp deleted file mode 100644 index 151f8270c47..00000000000 --- a/src/server/scripts/EasternKingdoms/zone_loch_modan.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/* ScriptData -SDName: Loch_Modan -SD%Complete: 100 -SDComment: Quest support: 3181 -SDCategory: Loch Modan -EndScriptData */ - -/* ContentData -npc_mountaineer_pebblebitty -EndContentData */ - -#include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "Player.h" - -/*###### -## npc_mountaineer_pebblebitty -######*/ - -#define GOSSIP_MP "Open the gate please, i need to get to Searing Gorge" - -#define GOSSIP_MP1 "But i need to get there, now open the gate!" -#define GOSSIP_MP2 "Ok, so what is this other way?" -#define GOSSIP_MP3 "Doesn't matter, i'm invulnerable." -#define GOSSIP_MP4 "Yes..." -#define GOSSIP_MP5 "Ok, i'll try to remember that." -#define GOSSIP_MP6 "A key? Ok!" - -class npc_mountaineer_pebblebitty : public CreatureScript -{ -public: - npc_mountaineer_pebblebitty() : CreatureScript("npc_mountaineer_pebblebitty") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->SEND_GOSSIP_MENU(1833, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->SEND_GOSSIP_MENU(1834, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - player->SEND_GOSSIP_MENU(1835, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); - player->SEND_GOSSIP_MENU(1836, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); - player->SEND_GOSSIP_MENU(1837, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+6: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); - player->SEND_GOSSIP_MENU(1838, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+7: - player->CLOSE_GOSSIP_MENU(); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (!player->GetQuestRewardStatus(3181) == 1) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_MP, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - -void AddSC_loch_modan() -{ - new npc_mountaineer_pebblebitty(); -} diff --git a/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp b/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp index 2d6d4da5aef..4a585bcb267 100644 --- a/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp +++ b/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp @@ -19,14 +19,12 @@ /* ScriptData SDName: Stormwind_City SD%Complete: 100 -SDComment: Quest support: 1640, 1447, 4185, 11223, 434. +SDComment: Quest support: 1640, 1447, 434. SDCategory: Stormwind City EndScriptData */ /* ContentData -npc_archmage_malin npc_bartleby -npc_lady_katrana_prestor npc_tyrion npc_tyrion_spybot npc_marzon_silent_blade @@ -40,50 +38,13 @@ EndContentData */ #include "Player.h" /*###### -## npc_archmage_malin -######*/ - -#define GOSSIP_ITEM_MALIN "Can you send me to Theramore? I have an urgent message for Lady Jaina from Highlord Bolvar." - -class npc_archmage_malin : public CreatureScript -{ -public: - npc_archmage_malin() : CreatureScript("npc_archmage_malin") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF) - { - player->CLOSE_GOSSIP_MENU(); - creature->CastSpell(player, 42711, true); - } - - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(11223) == QUEST_STATUS_COMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_MALIN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - -/*###### ## npc_bartleby ######*/ enum Bartleby { - FACTION_ENEMY = 168, - QUEST_BEAT = 1640 + FACTION_ENEMY = 168, + QUEST_BEAT = 1640 }; class npc_bartleby : public CreatureScript @@ -148,71 +109,18 @@ public: }; /*###### -## npc_lady_katrana_prestor -######*/ - -#define GOSSIP_ITEM_KAT_1 "Pardon the intrusion, Lady Prestor, but Highlord Bolvar suggested that I seek your advice." -#define GOSSIP_ITEM_KAT_2 "My apologies, Lady Prestor." -#define GOSSIP_ITEM_KAT_3 "Begging your pardon, Lady Prestor. That was not my intent." -#define GOSSIP_ITEM_KAT_4 "Thank you for your time, Lady Prestor." - -class npc_lady_katrana_prestor : public CreatureScript -{ -public: - npc_lady_katrana_prestor() : CreatureScript("npc_lady_katrana_prestor") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAT_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->SEND_GOSSIP_MENU(2694, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAT_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->SEND_GOSSIP_MENU(2695, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAT_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->SEND_GOSSIP_MENU(2696, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->CLOSE_GOSSIP_MENU(); - player->AreaExploredOrEventHappens(4185); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(4185) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_KAT_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - - player->SEND_GOSSIP_MENU(2693, creature->GetGUID()); - - return true; - } -}; - -/*###### ## npc_lord_gregor_lescovar ######*/ enum LordGregorLescovar { - SAY_GUARD_2 = 0, - SAY_LESCOVAR_2 = 0, - SAY_LESCOVAR_3 = 1, - SAY_LESCOVAR_4 = 2, - SAY_MARZON_1 = 0, - SAY_MARZON_2 = 1, - SAY_TYRION_2 = 1, + SAY_GUARD_2 = 0, + SAY_LESCOVAR_2 = 0, + SAY_LESCOVAR_3 = 1, + SAY_LESCOVAR_4 = 2, + SAY_MARZON_1 = 0, + SAY_MARZON_2 = 1, + SAY_TYRION_2 = 1, NPC_STORMWIND_ROYAL = 1756, NPC_MARZON_BLADE = 1755, @@ -650,9 +558,7 @@ public: void AddSC_stormwind_city() { - new npc_archmage_malin(); new npc_bartleby(); - new npc_lady_katrana_prestor(); new npc_tyrion(); new npc_tyrion_spybot(); new npc_lord_gregor_lescovar(); diff --git a/src/server/scripts/Events/CMakeLists.txt b/src/server/scripts/Events/CMakeLists.txt deleted file mode 100644 index 1c9e5cfe8e1..00000000000 --- a/src/server/scripts/Events/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB_RECURSE sources_Events Events/*.cpp Events/*.h) - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - ${sources_Events} -) - -message(" -> Prepared: Events") diff --git a/src/server/scripts/Events/childrens_week.cpp b/src/server/scripts/Events/childrens_week.cpp index 4b93f5b4fbb..f61e175b8fc 100644 --- a/src/server/scripts/Events/childrens_week.cpp +++ b/src/server/scripts/Events/childrens_week.cpp @@ -639,6 +639,12 @@ class npc_elder_kekek : public CreatureScript } }; +enum TheEtymidian +{ + SAY_ACTIVATION = 0, + QUEST_THE_ACTIVATION_RUNE = 12547 +}; + /*###### ## npc_the_etymidian ## @todo A red crystal as a gift for the great one should be spawned during the event. @@ -668,10 +674,20 @@ class npc_the_etymidian : public CreatureScript Initialize(); } + void sQuestReward(Player* /*player*/, Quest const* quest, uint32 /*opt*/) override + { + if (quest->GetQuestId() != QUEST_THE_ACTIVATION_RUNE) + return; + + Talk(SAY_ACTIVATION); + } + void MoveInLineOfSight(Unit* who) override { if (!phase && who && who->GetDistance2d(me) < 10.0f) + { if (Player* player = who->ToPlayer()) + { if (player->GetQuestStatus(QUEST_MEETING_A_GREAT_ONE) == QUEST_STATUS_INCOMPLETE) { playerGUID = player->GetGUID(); @@ -679,6 +695,8 @@ class npc_the_etymidian : public CreatureScript if (orphanGUID) phase = 1; } + } + } } void UpdateAI(uint32 diff) override @@ -734,7 +752,6 @@ class npc_the_etymidian : public CreatureScript int8 phase; ObjectGuid playerGUID; ObjectGuid orphanGUID; - }; CreatureAI* GetAI(Creature* creature) const override diff --git a/src/server/scripts/Events/events_script_loader.cpp b/src/server/scripts/Events/events_script_loader.cpp new file mode 100644 index 00000000000..625c08f5389 --- /dev/null +++ b/src/server/scripts/Events/events_script_loader.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_event_childrens_week(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddEventsScripts() +{ + AddSC_event_childrens_week(); +} diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp index b0d6e782052..03c957fa221 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp @@ -174,7 +174,7 @@ public: if (state == DONE) if (GameObject* go = instance->GetGameObject(shrineOfGelihastGUID)) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - break; + break; case DATA_AKU_MAI: if (state == DONE) if (GameObject* go = instance->GetGameObject(altarOfTheDeepsGUID)) diff --git a/src/server/scripts/Kalimdor/CMakeLists.txt b/src/server/scripts/Kalimdor/CMakeLists.txt deleted file mode 100644 index 2d1b4b49649..00000000000 --- a/src/server/scripts/Kalimdor/CMakeLists.txt +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - Kalimdor/zone_stonetalon_mountains.cpp - Kalimdor/zone_silithus.cpp - Kalimdor/zone_moonglade.cpp - Kalimdor/RazorfenDowns/razorfen_downs.cpp - Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp - Kalimdor/RazorfenDowns/boss_tuten_kash.cpp - Kalimdor/RazorfenDowns/boss_mordresh_fire_eye.cpp - Kalimdor/RazorfenDowns/boss_glutton.cpp - Kalimdor/RazorfenDowns/boss_amnennar_the_coldbringer.cpp - Kalimdor/RazorfenDowns/razorfen_downs.h - Kalimdor/ZulFarrak/zulfarrak.cpp - Kalimdor/ZulFarrak/instance_zulfarrak.cpp - Kalimdor/ZulFarrak/boss_zum_rah.cpp - Kalimdor/ZulFarrak/zulfarrak.h - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp - Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.h - Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h - Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp - Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp - Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h - Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h - Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp - Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp - Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp - Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp - Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp - Kalimdor/BlackfathomDeeps/boss_kelris.cpp - Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp - Kalimdor/BlackfathomDeeps/boss_gelihast.cpp - Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp - Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp - Kalimdor/BlackfathomDeeps/blackfathom_deeps.h - Kalimdor/zone_azuremyst_isle.cpp - Kalimdor/zone_orgrimmar.cpp - Kalimdor/zone_desolace.cpp - Kalimdor/zone_feralas.cpp - Kalimdor/Maraudon/boss_princess_theradras.cpp - Kalimdor/Maraudon/boss_landslide.cpp - Kalimdor/Maraudon/boss_celebras_the_cursed.cpp - Kalimdor/Maraudon/boss_noxxion.cpp - Kalimdor/Maraudon/instance_maraudon.cpp - Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp - Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp - Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp - Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp - Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp - Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp - Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp - Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp - Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h - Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp - Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp - Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp - Kalimdor/zone_darkshore.cpp - Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp - Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp - Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp - Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp - Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp - Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp - Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h - Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp - Kalimdor/zone_bloodmyst_isle.cpp - Kalimdor/zone_thunder_bluff.cpp - Kalimdor/zone_azshara.cpp - Kalimdor/RazorfenKraul/razorfen_kraul.h - Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp - Kalimdor/RazorfenKraul/razorfen_kraul.cpp - Kalimdor/zone_the_barrens.cpp - Kalimdor/zone_ungoro_crater.cpp - Kalimdor/WailingCaverns/wailing_caverns.h - Kalimdor/WailingCaverns/instance_wailing_caverns.cpp - Kalimdor/WailingCaverns/wailing_caverns.cpp - Kalimdor/zone_durotar.cpp - Kalimdor/zone_felwood.cpp - Kalimdor/boss_azuregos.cpp - Kalimdor/zone_tanaris.cpp - Kalimdor/zone_dustwallow_marsh.cpp - Kalimdor/zone_winterspring.cpp - Kalimdor/zone_thousand_needles.cpp - Kalimdor/zone_ashenvale.cpp - Kalimdor/OnyxiasLair/boss_onyxia.cpp - Kalimdor/OnyxiasLair/onyxias_lair.h - Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp - Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp - Kalimdor/DireMaul/instance_dire_maul.cpp -) - -message(" -> Prepared: Kalimdor") diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp index 6b2142a8095..c326710e820 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp @@ -650,7 +650,7 @@ void hyjalAI::SpawnVeins() return; for (uint8 i = 0; i < 7; ++i) { - GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7], 0); + GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], G3D::Quat(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i]=gem->GetGUID(); } @@ -662,7 +662,7 @@ void hyjalAI::SpawnVeins() return; for (uint8 i = 7; i < 14; ++i) { - GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7], 0); + GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], G3D::Quat(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i] = gem->GetGUID(); } @@ -725,7 +725,7 @@ void hyjalAI::UpdateAI(uint32 diff) HideNearPos(me->GetPositionX(), me->GetPositionY()); HideNearPos(5037.76f, -1889.71f); for (uint8 i = 0; i < 92; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7], 0); + me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], G3D::Quat(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); } else me->SetVisible(true); @@ -738,7 +738,7 @@ void hyjalAI::UpdateAI(uint32 diff) HideNearPos(5563, -2763.19f); HideNearPos(5542.2f, -2629.36f); for (uint8 i = 0; i < 65; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7], 0); + me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], G3D::Quat(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); } else me->SetVisible(true); @@ -1042,7 +1042,7 @@ void hyjalAI::DoOverrun(uint32 faction, const uint32 diff) { case 0://alliance for (uint8 i = 0; i < 92; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7], 0); + me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], G3D::Quat(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); for (uint8 i = 0; i < 25; ++i)//summon 25 ghouls { @@ -1083,7 +1083,7 @@ void hyjalAI::DoOverrun(uint32 faction, const uint32 diff) break; case 1://horde for (uint8 i = 0; i < 65; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7], 0); + me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], G3D::Quat(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); for (uint8 i = 0; i < 26; ++i)//summon infernals { diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h index 55b85801652..54d3c53039e 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h @@ -121,15 +121,15 @@ struct hyjalAI : public npc_escortAI void Initialize(); - void Reset(); // Generically used to reset our variables. Do *not* call in EnterEvadeMode as this may make problems if the raid is still in combat + void Reset() override; // Generically used to reset our variables. Do *not* call in EnterEvadeMode as this may make problems if the raid is still in combat - void EnterEvadeMode(EvadeReason /*why*/ = EVADE_REASON_OTHER); // Send creature back to spawn location and evade. + void EnterEvadeMode(EvadeReason /*why*/ = EVADE_REASON_OTHER) override; // Send creature back to spawn location and evade. - void EnterCombat(Unit* /*who*/); // Used to reset cooldowns for our spells and to inform the raid that we're under attack + void EnterCombat(Unit* /*who*/) override; // Used to reset cooldowns for our spells and to inform the raid that we're under attack - void UpdateAI(uint32 diff); // Called to summon waves, check for boss deaths and to cast our spells. + void UpdateAI(uint32 diff) override; // Called to summon waves, check for boss deaths and to cast our spells. - void JustDied(Unit* /*killer*/); // Called on death, informs the raid that they have failed. + void JustDied(Unit* /*killer*/) override; // Called on death, informs the raid that they have failed. void SetFaction(uint32 _faction) // Set the faction to either Alliance or Horde in Hyjal { @@ -140,13 +140,13 @@ struct hyjalAI : public npc_escortAI void SpawnVeins(); void DeSpawnVeins(); - void JustSummoned(Creature* summoned); - void SummonedCreatureDespawn(Creature* summoned); + void JustSummoned(Creature* summoned) override; + void SummonedCreatureDespawn(Creature* summoned) override; void HideNearPos(float x, float y); void RespawnNearPos(float x, float y); - void WaypointReached(uint32 waypointId); + void WaypointReached(uint32 waypointId) override; void DoOverrun(uint32 faction, const uint32 diff); - void MoveInLineOfSight(Unit* who); + void MoveInLineOfSight(Unit* who) override; void SummonCreature(uint32 entry, float Base[4][3]); // Summons a creature for that wave in that base diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.h b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.h index 5275c07f63a..f29851e7cea 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.h @@ -25,11 +25,11 @@ struct hyjal_trashAI : public npc_escortAI { hyjal_trashAI(Creature* creature); - void UpdateAI(uint32 diff); + void UpdateAI(uint32 diff) override; - void JustDied(Unit* /*killer*/); + void JustDied(Unit* /*killer*/) override; - void DamageTaken(Unit* done_by, uint32 &damage); + void DamageTaken(Unit* done_by, uint32 &damage) override; public: InstanceScript* instance; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp index 074ea781838..f76e65c3423 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp @@ -1256,7 +1256,7 @@ class npc_crate_helper : public CreatureScript instance->SetData(DATA_CRATE_COUNT, instance->GetData(DATA_CRATE_COUNT) + 1); if (GameObject* crate = me->FindNearestGameObject(GO_SUSPICIOUS_CRATE, 5.0f)) { - crate->SummonGameObject(GO_PLAGUED_CRATE, crate->GetPositionX(), crate->GetPositionY(), crate->GetPositionZ(), crate->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, DAY); + crate->SummonGameObject(GO_PLAGUED_CRATE, *crate, G3D::Quat(), DAY); crate->Delete(); } } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp index 44cbdec2cb5..8e53ab06ca5 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp @@ -479,12 +479,12 @@ public: void DoMount() { me->Mount(SKARLOC_MOUNT_MODEL); - me->SetSpeed(MOVE_RUN, SPEED_MOUNT); + me->SetSpeedRate(MOVE_RUN, SPEED_MOUNT); } void DoUnmount() { me->Dismount(); - me->SetSpeed(MOVE_RUN, SPEED_RUN); + me->SetSpeedRate(MOVE_RUN, SPEED_RUN); } void EnterCombat(Unit* /*who*/) override { @@ -535,12 +535,12 @@ public: if (!UpdateVictim()) return; - /// @todo add his abilities'n-crap here - if (!LowHp && HealthBelowPct(20)) - { - Talk(SAY_TH_RANDOM_LOW_HP); - LowHp = true; - } + /// @todo add his abilities'n-crap here + if (!LowHp && HealthBelowPct(20)) + { + Talk(SAY_TH_RANDOM_LOW_HP); + LowHp = true; + } } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp index 8715f3ca0f6..4d0f80d502d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp @@ -106,33 +106,33 @@ public: if (!UpdateVictim()) return; - events.Update(diff); + events.Update(diff); - if (me->HasUnitState(UNIT_STATE_CASTING)) - return; + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) { - switch (eventId) - { - case EVENT_SANDBREATH: - DoCastVictim(SPELL_SAND_BREATH); - events.ScheduleEvent(EVENT_SANDBREATH, urand(15000, 25000)); - break; - case EVENT_TIMESTOP: - DoCastVictim(SPELL_TIME_STOP); - events.ScheduleEvent(EVENT_TIMESTOP, urand(20000, 35000)); - break; - case EVENT_FRENZY: - Talk(EMOTE_FRENZY); - DoCast(me, SPELL_ENRAGE); - events.ScheduleEvent(EVENT_FRENZY, urand(20000, 35000)); - break; - default: - break; - } + case EVENT_SANDBREATH: + DoCastVictim(SPELL_SAND_BREATH); + events.ScheduleEvent(EVENT_SANDBREATH, urand(15000, 25000)); + break; + case EVENT_TIMESTOP: + DoCastVictim(SPELL_TIME_STOP); + events.ScheduleEvent(EVENT_TIMESTOP, urand(20000, 35000)); + break; + case EVENT_FRENZY: + Talk(EMOTE_FRENZY); + DoCast(me, SPELL_ENRAGE); + events.ScheduleEvent(EVENT_FRENZY, urand(20000, 35000)); + break; + default: + break; } - DoMeleeAttackIfReady(); + } + DoMeleeAttackIfReady(); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp index 2befdabe550..844ce239bdf 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp @@ -107,36 +107,36 @@ public: if (!UpdateVictim()) return; - events.Update(diff); + events.Update(diff); - if (me->HasUnitState(UNIT_STATE_CASTING)) - return; + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) { - switch (eventId) - { - case EVENT_HASTE: - DoCast(me, SPELL_HASTE); - events.ScheduleEvent(EVENT_HASTE, urand(20000, 25000)); - break; - case EVENT_MORTAL_WOUND: - DoCast(me, SPELL_MORTAL_WOUND); - events.ScheduleEvent(EVENT_MORTAL_WOUND, urand(10000, 20000)); - break; - case EVENT_WING_BUFFET: - DoCast(me, SPELL_WING_BUFFET); - events.ScheduleEvent(EVENT_WING_BUFFET, urand(20000, 30000)); - break; - case EVENT_SPELL_REFLECTION: // Only in Heroic - DoCast(me, SPELL_REFLECT); - events.ScheduleEvent(EVENT_SPELL_REFLECTION, urand(25000, 35000)); - break; - default: - break; - } + case EVENT_HASTE: + DoCast(me, SPELL_HASTE); + events.ScheduleEvent(EVENT_HASTE, urand(20000, 25000)); + break; + case EVENT_MORTAL_WOUND: + DoCast(me, SPELL_MORTAL_WOUND); + events.ScheduleEvent(EVENT_MORTAL_WOUND, urand(10000, 20000)); + break; + case EVENT_WING_BUFFET: + DoCast(me, SPELL_WING_BUFFET); + events.ScheduleEvent(EVENT_WING_BUFFET, urand(20000, 30000)); + break; + case EVENT_SPELL_REFLECTION: // Only in Heroic + DoCast(me, SPELL_REFLECT); + events.ScheduleEvent(EVENT_SPELL_REFLECTION, urand(25000, 35000)); + break; + default: + break; } - DoMeleeAttackIfReady(); + } + DoMeleeAttackIfReady(); } }; diff --git a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp index 00a622f1319..558b6c10a61 100644 --- a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp +++ b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp @@ -25,20 +25,49 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +// Bosses (East) +// 0 - Pusillin +// 1 - Lethtendris +// 2 - Hydrospawn +// 3 - Zevrim Thornhoof +// 4 - Alzzin the Wildshaper + +// West +// 5 - Tendris Warpwood +// 6 - Magister Kalendris +// 7 - Tsu'zee +// 8 - Illyanna Ravenoak +// 9 - Immol'thar +// 10 - Prince Tortheldrin + +// North +// 11 - Guard Mol'dar +// 12 - Stomper Kreeg +// 13 - Guard Fengus +// 14 - Guard Slip'kik +// 15 - Captain Kromcrush +// 16 - King Gordok + +uint8 const EncounterCount = 17; + class instance_dire_maul : public InstanceMapScript { public: instance_dire_maul() : InstanceMapScript("instance_dire_maul", 429) { } + struct instance_dire_maul_InstanceMapScript : public InstanceScript + { + instance_dire_maul_InstanceMapScript(Map* map) : InstanceScript(map) + { + SetBossNumber(EncounterCount); + } + }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_dire_maul_InstanceMapScript(map); } - struct instance_dire_maul_InstanceMapScript : public InstanceScript - { - instance_dire_maul_InstanceMapScript(Map* map) : InstanceScript(map) { } - }; }; void AddSC_instance_dire_maul() diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp index 7da15b1fdce..71ebe870e3d 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp @@ -205,7 +205,7 @@ public: PointData = GetMoveData(); MovePoint = PointData->LocIdEnd; - me->SetSpeed(MOVE_FLIGHT, 1.5f); + me->SetSpeedRate(MOVE_FLIGHT, 1.5f); me->GetMotionMaster()->MovePoint(8, MiddleRoomLocation); } } @@ -220,7 +220,7 @@ public: PointData = GetMoveData(); if (PointData) { - me->SetSpeed(MOVE_FLIGHT, 1.0f); + me->SetSpeedRate(MOVE_FLIGHT, 1.0f); me->GetMotionMaster()->MovePoint(PointData->LocId, PointData->fX, PointData->fY, PointData->fZ); } break; @@ -250,7 +250,7 @@ public: if (Creature * trigger = me->SummonCreature(NPC_TRIGGER, MiddleRoomLocation, TEMPSUMMON_CORPSE_DESPAWN)) triggerGUID = trigger->GetGUID(); me->GetMotionMaster()->MoveTakeoff(11, Phase2Floating); - me->SetSpeed(MOVE_FLIGHT, 1.0f); + me->SetSpeedRate(MOVE_FLIGHT, 1.0f); Talk(SAY_PHASE_2_TRANS); instance->SetData(DATA_ONYXIA_PHASE, Phase); events.ScheduleEvent(EVENT_WHELP_SPAWN, 5000); diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp index b579f9fc608..e8b101b5057 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp @@ -204,7 +204,7 @@ public: case EVENT_COMPLETE: { DoCast(me, SPELL_IDOM_ROOM_CAMERA_SHAKE); - me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, 0, 0, 0.9238796f, 0.3826832f, 3600); + me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, G3D::Quat(0.f, 0.f, 0.9238796f, 0.3826832f), 3600); std::list<WorldObject*> ClusterList; Trinity::AllWorldObjectsInRange objects(me, 50.0f); Trinity::WorldObjectListSearcher<Trinity::AllWorldObjectsInRange> searcher(me, ClusterList, objects); diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp index b192ff8ef4d..a220468e513 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp @@ -190,11 +190,7 @@ class boss_ossirian : public CreatureScript if (Creature* Trigger = me->GetMap()->SummonCreature(NPC_OSSIRIAN_TRIGGER, CrystalCoordinates[CrystalIterator])) { TriggerGUID = Trigger->GetGUID(); - if (GameObject* Crystal = Trigger->SummonGameObject(GO_OSSIRIAN_CRYSTAL, - CrystalCoordinates[CrystalIterator].GetPositionX(), - CrystalCoordinates[CrystalIterator].GetPositionY(), - CrystalCoordinates[CrystalIterator].GetPositionZ(), - 0, 0, 0, 0, 0, uint32(-1))) + if (GameObject* Crystal = Trigger->SummonGameObject(GO_OSSIRIAN_CRYSTAL, CrystalCoordinates[CrystalIterator], G3D::Quat(), uint32(-1))) { CrystalGUID = Crystal->GetGUID(); ++CrystalIterator; diff --git a/src/server/scripts/Kalimdor/kalimdor_script_loader.cpp b/src/server/scripts/Kalimdor/kalimdor_script_loader.cpp new file mode 100644 index 00000000000..87edf4781d4 --- /dev/null +++ b/src/server/scripts/Kalimdor/kalimdor_script_loader.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_blackfathom_deeps(); //Blackfathom Depths +void AddSC_boss_gelihast(); +void AddSC_boss_kelris(); +void AddSC_boss_aku_mai(); +void AddSC_instance_blackfathom_deeps(); +void AddSC_hyjal(); //CoT Battle for Mt. Hyjal +void AddSC_boss_archimonde(); +void AddSC_instance_mount_hyjal(); +void AddSC_hyjal_trash(); +void AddSC_boss_rage_winterchill(); +void AddSC_boss_anetheron(); +void AddSC_boss_kazrogal(); +void AddSC_boss_azgalor(); +void AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad +void AddSC_boss_epoch_hunter(); +void AddSC_boss_lieutenant_drake(); +void AddSC_instance_old_hillsbrad(); +void AddSC_old_hillsbrad(); +void AddSC_boss_aeonus(); //CoT The Black Morass +void AddSC_boss_chrono_lord_deja(); +void AddSC_boss_temporus(); +void AddSC_the_black_morass(); +void AddSC_instance_the_black_morass(); +void AddSC_boss_epoch(); //CoT Culling Of Stratholme +void AddSC_boss_infinite_corruptor(); +void AddSC_boss_salramm(); +void AddSC_boss_mal_ganis(); +void AddSC_boss_meathook(); +void AddSC_culling_of_stratholme(); +void AddSC_instance_culling_of_stratholme(); +void AddSC_instance_dire_maul(); //Dire Maul +void AddSC_instance_ragefire_chasm(); //Ragefire Chasm +void AddSC_boss_celebras_the_cursed(); //Maraudon +void AddSC_boss_landslide(); +void AddSC_boss_noxxion(); +void AddSC_boss_ptheradras(); +void AddSC_instance_maraudon(); +void AddSC_boss_onyxia(); //Onyxia's Lair +void AddSC_instance_onyxias_lair(); +void AddSC_boss_tuten_kash(); //Razorfen Downs +void AddSC_boss_mordresh_fire_eye(); +void AddSC_boss_glutton(); +void AddSC_boss_amnennar_the_coldbringer(); +void AddSC_razorfen_downs(); +void AddSC_instance_razorfen_downs(); +void AddSC_razorfen_kraul(); //Razorfen Kraul +void AddSC_instance_razorfen_kraul(); +void AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj +void AddSC_boss_rajaxx(); +void AddSC_boss_moam(); +void AddSC_boss_buru(); +void AddSC_boss_ayamiss(); +void AddSC_boss_ossirian(); +void AddSC_instance_ruins_of_ahnqiraj(); +void AddSC_boss_cthun(); //Temple of ahn'qiraj +void AddSC_boss_viscidus(); +void AddSC_boss_fankriss(); +void AddSC_boss_huhuran(); +void AddSC_bug_trio(); +void AddSC_boss_sartura(); +void AddSC_boss_skeram(); +void AddSC_boss_twinemperors(); +void AddSC_boss_ouro(); +void AddSC_npc_anubisath_sentinel(); +void AddSC_instance_temple_of_ahnqiraj(); +void AddSC_wailing_caverns(); //Wailing caverns +void AddSC_instance_wailing_caverns(); +void AddSC_boss_zum_rah(); //Zul'Farrak +void AddSC_zulfarrak(); +void AddSC_instance_zulfarrak(); + +void AddSC_ashenvale(); +void AddSC_azshara(); +void AddSC_azuremyst_isle(); +void AddSC_bloodmyst_isle(); +void AddSC_boss_azuregos(); +void AddSC_darkshore(); +void AddSC_desolace(); +void AddSC_durotar(); +void AddSC_dustwallow_marsh(); +void AddSC_felwood(); +void AddSC_feralas(); +void AddSC_moonglade(); +void AddSC_orgrimmar(); +void AddSC_silithus(); +void AddSC_stonetalon_mountains(); +void AddSC_tanaris(); +void AddSC_the_barrens(); +void AddSC_thousand_needles(); +void AddSC_thunder_bluff(); +void AddSC_ungoro_crater(); +void AddSC_winterspring(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddKalimdorScripts() +{ + AddSC_blackfathom_deeps(); //Blackfathom Depths + AddSC_boss_gelihast(); + AddSC_boss_kelris(); + AddSC_boss_aku_mai(); + AddSC_instance_blackfathom_deeps(); + AddSC_hyjal(); //CoT Battle for Mt. Hyjal + AddSC_boss_archimonde(); + AddSC_instance_mount_hyjal(); + AddSC_hyjal_trash(); + AddSC_boss_rage_winterchill(); + AddSC_boss_anetheron(); + AddSC_boss_kazrogal(); + AddSC_boss_azgalor(); + AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad + AddSC_boss_epoch_hunter(); + AddSC_boss_lieutenant_drake(); + AddSC_instance_old_hillsbrad(); + AddSC_old_hillsbrad(); + AddSC_boss_aeonus(); //CoT The Black Morass + AddSC_boss_chrono_lord_deja(); + AddSC_boss_temporus(); + AddSC_the_black_morass(); + AddSC_instance_the_black_morass(); + AddSC_boss_epoch(); //CoT Culling Of Stratholme + AddSC_boss_infinite_corruptor(); + AddSC_boss_salramm(); + AddSC_boss_mal_ganis(); + AddSC_boss_meathook(); + AddSC_culling_of_stratholme(); + AddSC_instance_culling_of_stratholme(); + AddSC_instance_dire_maul(); //Dire Maul + AddSC_instance_ragefire_chasm(); //Ragefire Chasm + AddSC_boss_celebras_the_cursed(); //Maraudon + AddSC_boss_landslide(); + AddSC_boss_noxxion(); + AddSC_boss_ptheradras(); + AddSC_instance_maraudon(); + AddSC_boss_onyxia(); //Onyxia's Lair + AddSC_instance_onyxias_lair(); + AddSC_boss_tuten_kash(); //Razorfen Downs + AddSC_boss_mordresh_fire_eye(); + AddSC_boss_glutton(); + AddSC_boss_amnennar_the_coldbringer(); + AddSC_razorfen_downs(); + AddSC_instance_razorfen_downs(); + AddSC_razorfen_kraul(); //Razorfen Kraul + AddSC_instance_razorfen_kraul(); + AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj + AddSC_boss_rajaxx(); + AddSC_boss_moam(); + AddSC_boss_buru(); + AddSC_boss_ayamiss(); + AddSC_boss_ossirian(); + AddSC_instance_ruins_of_ahnqiraj(); + AddSC_boss_cthun(); //Temple of ahn'qiraj + AddSC_boss_viscidus(); + AddSC_boss_fankriss(); + AddSC_boss_huhuran(); + AddSC_bug_trio(); + AddSC_boss_sartura(); + AddSC_boss_skeram(); + AddSC_boss_twinemperors(); + AddSC_boss_ouro(); + AddSC_npc_anubisath_sentinel(); + AddSC_instance_temple_of_ahnqiraj(); + AddSC_wailing_caverns(); //Wailing caverns + AddSC_instance_wailing_caverns(); + AddSC_boss_zum_rah(); //Zul'Farrak + AddSC_zulfarrak(); + AddSC_instance_zulfarrak(); + + AddSC_ashenvale(); + AddSC_azshara(); + AddSC_azuremyst_isle(); + AddSC_bloodmyst_isle(); + AddSC_boss_azuregos(); + AddSC_darkshore(); + AddSC_desolace(); + AddSC_durotar(); + AddSC_dustwallow_marsh(); + AddSC_felwood(); + AddSC_feralas(); + AddSC_moonglade(); + AddSC_orgrimmar(); + AddSC_silithus(); + AddSC_stonetalon_mountains(); + AddSC_tanaris(); + AddSC_the_barrens(); + AddSC_thousand_needles(); + AddSC_thunder_bluff(); + AddSC_ungoro_crater(); + AddSC_winterspring(); +} diff --git a/src/server/scripts/Kalimdor/zone_azshara.cpp b/src/server/scripts/Kalimdor/zone_azshara.cpp index 1ed95c16a0d..4847ac46542 100644 --- a/src/server/scripts/Kalimdor/zone_azshara.cpp +++ b/src/server/scripts/Kalimdor/zone_azshara.cpp @@ -404,7 +404,7 @@ public: DoCast(me, SPELL_PERIODIC_DEPTH_CHARGE); me->SetHover(true); me->SetSwim(true); - me->SetSpeed(MOVE_RUN, 0.85f, true); + me->SetSpeedRate(MOVE_RUN, 0.85f); me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MovePoint(CurrWP, WPs[CurrWP]); Escape = true; diff --git a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp index 273e81d83c0..a7b2b156128 100644 --- a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp +++ b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp @@ -240,11 +240,6 @@ class npc_sironas : public CreatureScript public: npc_sironas() : CreatureScript("npc_sironas") { } - CreatureAI* GetAI(Creature* creature) const - { - return new npc_sironasAI(creature); - } - struct npc_sironasAI : public ScriptedAI { npc_sironasAI(Creature* creature) : ScriptedAI(creature) { } @@ -343,6 +338,11 @@ public: GuidList _beamGuidList; EventMap _events; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_sironasAI(creature); + } }; /*###### @@ -354,11 +354,6 @@ class npc_demolitionist_legoso : public CreatureScript public: npc_demolitionist_legoso() : CreatureScript("npc_demolitionist_legoso") { } - CreatureAI* GetAI(Creature* creature) const - { - return new npc_demolitionist_legosoAI(creature); - } - struct npc_demolitionist_legosoAI : public npc_escortAI { npc_demolitionist_legosoAI(Creature* creature) : npc_escortAI(creature) @@ -513,7 +508,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i].m_positionX, ExplosivesPos[0][i].m_positionY, ExplosivesPos[0][i].m_positionZ, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], G3D::Quat(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } me->HandleEmoteCommand(EMOTE_ONESHOT_NONE); // reset anim state @@ -609,7 +604,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i].m_positionX, ExplosivesPos[1][i].m_positionY, ExplosivesPos[1][i].m_positionZ, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], G3D::Quat(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } Talk(SAY_LEGOSO_15); @@ -812,6 +807,11 @@ public: GuidList _explosivesGuids; EventMap _events; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_demolitionist_legosoAI(creature); + } }; void AddSC_bloodmyst_isle() diff --git a/src/server/scripts/Kalimdor/zone_desolace.cpp b/src/server/scripts/Kalimdor/zone_desolace.cpp index 621e0b0a585..3f4a905147f 100644 --- a/src/server/scripts/Kalimdor/zone_desolace.cpp +++ b/src/server/scripts/Kalimdor/zone_desolace.cpp @@ -66,7 +66,6 @@ public: npc_aged_dying_ancient_kodoAI(Creature* creature) : ScriptedAI(creature) { } void MoveInLineOfSight(Unit* who) override - { if (who->GetEntry() == NPC_SMEED && me->IsWithinDistInMap(who, 10.0f) && !me->HasAura(SPELL_KODO_KOMBO_GOSSIP)) { @@ -90,7 +89,7 @@ public: me->UpdateEntry(NPC_TAMED_KODO); me->CombatStop(); me->DeleteThreatList(); - me->SetSpeed(MOVE_RUN, 0.6f, true); + me->SetSpeedRate(MOVE_RUN, 0.6f); me->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, me->GetFollowAngle()); me->setActive(true); } @@ -226,37 +225,9 @@ public: } }; -/*###### -## go_demon_portal -######*/ - -enum DemonPortal -{ - NPC_DEMON_GUARDIAN = 11937, - QUEST_PORTAL_OF_THE_LEGION = 5581 -}; - -class go_demon_portal : public GameObjectScript -{ - public: - go_demon_portal() : GameObjectScript("go_demon_portal") { } - - bool OnGossipHello(Player* player, GameObject* go) override - { - if (player->GetQuestStatus(QUEST_PORTAL_OF_THE_LEGION) == QUEST_STATUS_INCOMPLETE && !go->FindNearestCreature(NPC_DEMON_GUARDIAN, 5.0f, true)) - { - if (Creature* guardian = player->SummonCreature(NPC_DEMON_GUARDIAN, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0)) - guardian->AI()->AttackStart(player); - } - - return true; - } -}; - void AddSC_desolace() { new npc_aged_dying_ancient_kodo(); new go_iruxos(); new npc_dalinda(); - new go_demon_portal(); } diff --git a/src/server/scripts/Kalimdor/zone_durotar.cpp b/src/server/scripts/Kalimdor/zone_durotar.cpp index 05caf9cca3a..62a041e7798 100644 --- a/src/server/scripts/Kalimdor/zone_durotar.cpp +++ b/src/server/scripts/Kalimdor/zone_durotar.cpp @@ -483,8 +483,8 @@ class spell_mount_check : public SpellScriptLoader else if (!owner->IsMounted() && target->IsMounted()) target->Dismount(); - target->SetSpeed(MOVE_RUN, owner->GetSpeedRate(MOVE_RUN)); - target->SetSpeed(MOVE_WALK, owner->GetSpeedRate(MOVE_WALK)); + target->SetSpeedRate(MOVE_RUN, owner->GetSpeedRate(MOVE_RUN)); + target->SetSpeedRate(MOVE_WALK, owner->GetSpeedRate(MOVE_WALK)); } void Register() override diff --git a/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp b/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp index 9df9f0b604a..be49778ee4a 100644 --- a/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp +++ b/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp @@ -24,7 +24,6 @@ SDCategory: Dustwallow Marsh EndScriptData */ /* ContentData -npc_lady_jaina_proudmoore npc_nat_pagle npc_private_hendel npc_cassa_crimsonwing - handled by npc_taxi @@ -39,49 +38,6 @@ EndContentData */ #include "WorldSession.h" /*###### -## npc_lady_jaina_proudmoore -######*/ - -enum LadyJaina -{ - QUEST_JAINAS_AUTOGRAPH = 558, - SPELL_JAINAS_AUTOGRAPH = 23122 -}; - -#define GOSSIP_ITEM_JAINA "I know this is rather silly but i have a young ward who is a bit shy and would like your autograph." - -class npc_lady_jaina_proudmoore : public CreatureScript -{ -public: - npc_lady_jaina_proudmoore() : CreatureScript("npc_lady_jaina_proudmoore") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_SENDER_INFO) - { - player->SEND_GOSSIP_MENU(7012, creature->GetGUID()); - player->CastSpell(player, SPELL_JAINAS_AUTOGRAPH, false); - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_JAINAS_AUTOGRAPH) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_JAINA, GOSSIP_SENDER_MAIN, GOSSIP_SENDER_INFO); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } - -}; - -/*###### ## npc_nat_pagle ######*/ @@ -417,7 +373,6 @@ class spell_energize_aoe : public SpellScriptLoader void AddSC_dustwallow_marsh() { - new npc_lady_jaina_proudmoore(); new npc_nat_pagle(); new npc_private_hendel(); new npc_zelfrax(); diff --git a/src/server/scripts/Kalimdor/zone_felwood.cpp b/src/server/scripts/Kalimdor/zone_felwood.cpp index bce9d62105c..2b42db4b697 100644 --- a/src/server/scripts/Kalimdor/zone_felwood.cpp +++ b/src/server/scripts/Kalimdor/zone_felwood.cpp @@ -19,12 +19,12 @@ /* ScriptData SDName: Felwood SD%Complete: 95 -SDComment: Quest support: 4101, 4102 +SDComment: Quest support: 7632 SDCategory: Felwood EndScriptData */ /* ContentData -npcs_riverbreeze_and_silversky +at_ancient_leaf EndContentData */ #include "ScriptMgr.h" @@ -33,74 +33,6 @@ EndContentData */ #include "Player.h" /*###### -## npcs_riverbreeze_and_silversky -######*/ - -#define GOSSIP_ITEM_BEACON "Please make me a Cenarion Beacon" - -enum RiverbreezeAndSilversky -{ - SPELL_CENARION_BEACON = 15120, - - NPC_ARATHANDRIS_SILVERSKY = 9528, - NPC_MAYBESS_RIVERBREEZE = 9529, - - QUEST_CLEASING_FELWOOD_A = 4101, - QUEST_CLEASING_FELWOOD_H = 4102 -}; - -class npcs_riverbreeze_and_silversky : public CreatureScript -{ -public: - npcs_riverbreeze_and_silversky() : CreatureScript("npcs_riverbreeze_and_silversky") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - { - player->CLOSE_GOSSIP_MENU(); - creature->CastSpell(player, SPELL_CENARION_BEACON, false); - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - uint32 creatureId = creature->GetEntry(); - - if (creatureId == NPC_ARATHANDRIS_SILVERSKY) - { - if (player->GetQuestRewardStatus(QUEST_CLEASING_FELWOOD_A)) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_BEACON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(2848, creature->GetGUID()); - } else if (player->GetTeam() == HORDE) - player->SEND_GOSSIP_MENU(2845, creature->GetGUID()); - else - player->SEND_GOSSIP_MENU(2844, creature->GetGUID()); - } - - if (creatureId == NPC_MAYBESS_RIVERBREEZE) - { - if (player->GetQuestRewardStatus(QUEST_CLEASING_FELWOOD_H)) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_BEACON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(2849, creature->GetGUID()); - } else if (player->GetTeam() == ALLIANCE) - player->SEND_GOSSIP_MENU(2843, creature->GetGUID()); - else - player->SEND_GOSSIP_MENU(2842, creature->GetGUID()); - } - - return true; - } -}; - -/*###### ## at_ancient_leaf ######*/ @@ -138,6 +70,5 @@ class at_ancient_leaf : public AreaTriggerScript void AddSC_felwood() { - new npcs_riverbreeze_and_silversky(); new at_ancient_leaf(); } diff --git a/src/server/scripts/Kalimdor/zone_feralas.cpp b/src/server/scripts/Kalimdor/zone_feralas.cpp index 3e67a95b503..3c6ab633f66 100644 --- a/src/server/scripts/Kalimdor/zone_feralas.cpp +++ b/src/server/scripts/Kalimdor/zone_feralas.cpp @@ -19,10 +19,15 @@ /* ScriptData SDName: Feralas SD%Complete: 100 -SDComment: Quest support: 2767, Special vendor Gregan Brewspewer +SDComment: Quest support: 2767, 2987 SDCategory: Feralas EndScriptData */ +/* ContentData +npc_oox22fe +spell_gordunni_trap +EndContentData */ + #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedEscortAI.h" @@ -32,44 +37,6 @@ EndScriptData */ #include "WorldSession.h" /*###### -## npc_gregan_brewspewer -######*/ - -#define GOSSIP_HELLO "Buy somethin', will ya?" - -class npc_gregan_brewspewer : public CreatureScript -{ -public: - npc_gregan_brewspewer() : CreatureScript("npc_gregan_brewspewer") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); - player->SEND_GOSSIP_MENU(2434, creature->GetGUID()); - } - if (action == GOSSIP_ACTION_TRADE) - player->GetSession()->SendListInventory(creature->GetGUID()); - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (creature->IsVendor() && player->GetQuestStatus(3909) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(2433, creature->GetGUID()); - return true; - } - -}; - -/*###### ## npc_oox22fe ######*/ @@ -183,6 +150,10 @@ public: }; +/*###### +## spell_gordunni_trap +######*/ + enum GordunniTrap { GO_GORDUNNI_DIRT_MOUND = 144064, @@ -199,12 +170,12 @@ class spell_gordunni_trap : public SpellScriptLoader void HandleDummy() { - if (Unit* caster = GetCaster()) - if (GameObject* chest = caster->SummonGameObject(GO_GORDUNNI_DIRT_MOUND, caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ(), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0)) - { - chest->SetSpellId(GetSpellInfo()->Id); - caster->RemoveGameObject(chest, false); - } + Unit* caster = GetCaster(); + if (GameObject* chest = caster->SummonGameObject(GO_GORDUNNI_DIRT_MOUND, *caster, G3D::Quat(), 0)) + { + chest->SetSpellId(GetSpellInfo()->Id); + caster->RemoveGameObject(chest, false); + } } void Register() override @@ -225,7 +196,6 @@ class spell_gordunni_trap : public SpellScriptLoader void AddSC_feralas() { - new npc_gregan_brewspewer(); new npc_oox22fe(); new spell_gordunni_trap(); } diff --git a/src/server/scripts/Kalimdor/zone_moonglade.cpp b/src/server/scripts/Kalimdor/zone_moonglade.cpp index 99a209b5f0a..531c657e1cb 100644 --- a/src/server/scripts/Kalimdor/zone_moonglade.cpp +++ b/src/server/scripts/Kalimdor/zone_moonglade.cpp @@ -19,15 +19,14 @@ /* ScriptData SDName: Moonglade SD%Complete: 100 -SDComment: Quest support: 30, 272, 5929, 5930, 10965. Special Flight Paths for Druid class. +SDComment: Quest support: 10965 SDCategory: Moonglade EndScriptData */ /* ContentData -npc_bunthen_plainswind -npc_silva_filnaveth npc_clintar_spirit -npc_clintar_dreamwalker +npc_omen +npc_giant_spotlight EndContentData */ #include "ScriptMgr.h" @@ -42,128 +41,6 @@ EndContentData */ #include "CellImpl.h" /*###### -## npc_bunthen_plainswind -######*/ - -enum Bunthen -{ - QUEST_SEA_LION_HORDE = 30, - QUEST_SEA_LION_ALLY = 272, - TAXI_PATH_ID_ALLY = 315, - TAXI_PATH_ID_HORDE = 316 -}; - -#define GOSSIP_ITEM_THUNDER "I'd like to fly to Thunder Bluff." -#define GOSSIP_ITEM_AQ_END "Do you know where I can find Half Pendant of Aquatic Endurance?" - -class npc_bunthen_plainswind : public CreatureScript -{ -public: - npc_bunthen_plainswind() : CreatureScript("npc_bunthen_plainswind") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF + 1: - player->CLOSE_GOSSIP_MENU(); - if (player->getClass() == CLASS_DRUID && player->GetTeam() == HORDE) - player->ActivateTaxiPathTo(TAXI_PATH_ID_HORDE); - break; - case GOSSIP_ACTION_INFO_DEF + 2: - player->SEND_GOSSIP_MENU(5373, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 3: - player->SEND_GOSSIP_MENU(5376, creature->GetGUID()); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (player->getClass() != CLASS_DRUID) - player->SEND_GOSSIP_MENU(4916, creature->GetGUID()); - else if (player->GetTeam() != HORDE) - { - if (player->GetQuestStatus(QUEST_SEA_LION_ALLY) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_AQ_END, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - - player->SEND_GOSSIP_MENU(4917, creature->GetGUID()); - } - else if (player->getClass() == CLASS_DRUID && player->GetTeam() == HORDE) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_THUNDER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - - if (player->GetQuestStatus(QUEST_SEA_LION_HORDE) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_AQ_END, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - - player->SEND_GOSSIP_MENU(4918, creature->GetGUID()); - } - return true; - } - -}; - -/*###### -## npc_silva_filnaveth -######*/ - -#define GOSSIP_ITEM_RUTHERAN "I'd like to fly to Rut'theran Village." -#define GOSSIP_ITEM_AQ_AGI "Do you know where I can find Half Pendant of Aquatic Agility?" - -class npc_silva_filnaveth : public CreatureScript -{ -public: - npc_silva_filnaveth() : CreatureScript("npc_silva_filnaveth") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF + 1: - player->CLOSE_GOSSIP_MENU(); - if (player->getClass() == CLASS_DRUID && player->GetTeam() == ALLIANCE) - player->ActivateTaxiPathTo(TAXI_PATH_ID_ALLY); - break; - case GOSSIP_ACTION_INFO_DEF + 2: - player->SEND_GOSSIP_MENU(5374, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 3: - player->SEND_GOSSIP_MENU(5375, creature->GetGUID()); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (player->getClass() != CLASS_DRUID) - player->SEND_GOSSIP_MENU(4913, creature->GetGUID()); - else if (player->GetTeam() != ALLIANCE) - { - if (player->GetQuestStatus(QUEST_SEA_LION_HORDE) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_AQ_AGI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - - player->SEND_GOSSIP_MENU(4915, creature->GetGUID()); - } - else if (player->getClass() == CLASS_DRUID && player->GetTeam() == ALLIANCE) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_RUTHERAN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - - if (player->GetQuestStatus(QUEST_SEA_LION_ALLY) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_AQ_AGI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - - player->SEND_GOSSIP_MENU(4914, creature->GetGUID()); - } - return true; - } - -}; - -/*###### ## npc_clintar_spirit ######*/ @@ -652,8 +529,6 @@ public: void AddSC_moonglade() { - new npc_bunthen_plainswind(); - new npc_silva_filnaveth(); new npc_clintar_spirit(); new npc_omen(); new npc_giant_spotlight(); diff --git a/src/server/scripts/Kalimdor/zone_orgrimmar.cpp b/src/server/scripts/Kalimdor/zone_orgrimmar.cpp index ac26aa1f811..9c531c1f1be 100644 --- a/src/server/scripts/Kalimdor/zone_orgrimmar.cpp +++ b/src/server/scripts/Kalimdor/zone_orgrimmar.cpp @@ -32,6 +32,9 @@ EndContentData */ #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "Player.h" +#include "Cell.h" +#include "CellImpl.h" +#include "GridNotifiers.h" /*###### ## npc_shenthul @@ -143,20 +146,30 @@ public: enum ThrallWarchief { - QUEST_6566 = 6566, - - SPELL_CHAIN_LIGHTNING = 16033, - SPELL_SHOCK = 16034 + GOSSIP_MENU_OPTION_ID_ALL = 0, + + OPTION_PLEASE_SHARE_YOUR = 3664, + OPTION_WHAT_DISCOVERIES = 3665, + OPTION_USURPER = 3666, + OPTION_WITH_ALL_DUE_RESPECT = 3667, + OPTION_I_I_DID_NOT_THINK_OF = 3668, + OPTION_I_LIVE_ONLY_TO_SERVE = 3669, + OPTION_OF_COURSE_WARCHIEF = 3670, + + GOSSIP_MEMBERS_OF_THE_HORDE = 4477, + GOSSIP_THE_SHATTERED_HAND = 5733, + GOSSIP_IT_WOULD_APPEAR_AS = 5734, + GOSSIP_THE_BROOD_MOTHER = 5735, + GOSSIP_SO_MUCH_TO_LEARN = 5736, + GOSSIP_I_DO_NOT_FAULT_YOU = 5737, + GOSSIP_NOW_PAY_ATTENTION = 5738, + + QUEST_WHAT_THE_WIND_CARRIES = 6566, + + SPELL_CHAIN_LIGHTNING = 16033, + SPELL_SHOCK = 16034 }; -#define GOSSIP_HTW "Please share your wisdom with me, Warchief." -#define GOSSIP_STW1 "What discoveries?" -#define GOSSIP_STW2 "Usurper?" -#define GOSSIP_STW3 "With all due respect, Warchief - why not allow them to be destroyed? Does this not strengthen our position?" -#define GOSSIP_STW4 "I... I did not think of it that way, Warchief." -#define GOSSIP_STW5 "I live only to serve, Warchief! My life is empty and meaningless without your guidance." -#define GOSSIP_STW6 "Of course, Warchief!" - /// @todo verify abilities/timers class npc_thrall_warchief : public CreatureScript { @@ -169,32 +182,32 @@ public: switch (action) { case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - player->SEND_GOSSIP_MENU(5733, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_WHAT_DISCOVERIES, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); + player->SEND_GOSSIP_MENU(GOSSIP_THE_SHATTERED_HAND, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - player->SEND_GOSSIP_MENU(5734, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_USURPER, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); + player->SEND_GOSSIP_MENU(GOSSIP_IT_WOULD_APPEAR_AS, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); - player->SEND_GOSSIP_MENU(5735, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_WITH_ALL_DUE_RESPECT, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); + player->SEND_GOSSIP_MENU(GOSSIP_THE_BROOD_MOTHER, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); - player->SEND_GOSSIP_MENU(5736, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_I_I_DID_NOT_THINK_OF, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); + player->SEND_GOSSIP_MENU(GOSSIP_SO_MUCH_TO_LEARN, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+6); - player->SEND_GOSSIP_MENU(5737, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_I_LIVE_ONLY_TO_SERVE, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+6); + player->SEND_GOSSIP_MENU(GOSSIP_I_DO_NOT_FAULT_YOU, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+6: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_STW6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+7); - player->SEND_GOSSIP_MENU(5738, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(OPTION_OF_COURSE_WARCHIEF, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+7); + player->SEND_GOSSIP_MENU(GOSSIP_NOW_PAY_ATTENTION, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+7: player->CLOSE_GOSSIP_MENU(); - player->AreaExploredOrEventHappens(QUEST_6566); + player->AreaExploredOrEventHappens(QUEST_WHAT_THE_WIND_CARRIES); break; } return true; @@ -205,10 +218,10 @@ public: if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); - if (player->GetQuestStatus(QUEST_6566) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HTW, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + if (player->GetQuestStatus(QUEST_WHAT_THE_WIND_CARRIES) == QUEST_STATUS_INCOMPLETE) + player->ADD_GOSSIP_ITEM_DB(OPTION_PLEASE_SHARE_YOUR, GOSSIP_MENU_OPTION_ID_ALL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); + player->SEND_GOSSIP_MENU(GOSSIP_MEMBERS_OF_THE_HORDE, creature->GetGUID()); return true; } @@ -263,8 +276,555 @@ public: }; +/* --------- Herald of War ------------- */ +enum CitizenEntries +{ + NPC_GRYSHKA = 31433, + NPC_OLVIA = 31425, + NPC_SANA = 31429, + NPC_FELIKA = 31427, + NPC_THATHUNG = 31430, + NPC_KAJA = 31423 +}; + +enum SceneEvents +{ + EVENT_SCENE_1 = 1, + EVENT_SCENE_2 = 2, + EVENT_SCENE_3 = 3, + EVENT_SCENE_4 = 4, + EVENT_SCENE_5 = 5, + EVENT_SCENE_6 = 6, + EVENT_SCENE_7 = 7, + EVENT_SCENE_8 = 8, + EVENT_SCENE_9 = 9, + EVENT_SCENE_10 = 10, + EVENT_SCENE_11 = 11, + EVENT_SCENE_12 = 12, + EVENT_SCENE_13 = 13, + EVENT_RESET = 14 +}; + +enum CitizenTalk +{ + SAY_GRYSHKA_1 = 0, // When can we reopen our shops? I'm losing gold here! + SAY_GRYSHKA_2 = 1, // "This is an outrage!" + SAY_OLVIA_1 = 0, // Where is the Warchief? + SAY_OLVIA_2 = 1, // What are all these Forsaken doing here? + SAY_FELIKA_1 = 0, // What is going on? + SAY_FELIKA_2 = 1, // This is an outrage! + SAY_THATHUNG = 0, // What is going on? + SAY_KAJA = 0, // Why is Thrall allowing this to happen to our city? + SAY_SANA = 0, // We demand answers! + SAY_RUNTHAK_1 = 0, // SILENCE! + SAY_RUNTHAK_2 = 1, // We are on the brink of all out war with the Alliance! + SAY_RUNTHAK_3 = 2, // Tragic events have unfolded in Northrend. The Warchief is doing all that he can to keep us safe. + SAY_RUNTHAK_4 = 3 // All services and shops are to remain closed until further notice! That is all! +}; + +class npc_overlord_runthak_orgrimmar : public CreatureScript +{ +public: + npc_overlord_runthak_orgrimmar() : CreatureScript("npc_overlord_runthak_orgrimmar") { } + + struct npc_overlord_runthak_orgrimmarAI : public ScriptedAI + { + npc_overlord_runthak_orgrimmarAI(Creature* creature) : ScriptedAI(creature) + { + inProgress = false; + } + + void Reset() override + { + inProgress = false; + me->GetMotionMaster()->MovePath(me->GetSpawnId() * 10, true); + events.Reset(); + } + + void MoveInLineOfSight(Unit* who) override + { + if (who->GetTypeId() == TYPEID_PLAYER && who->IsWithinDist(me, 20.0f) && !inProgress) + { + inProgress = true; + events.ScheduleEvent(EVENT_SCENE_1, 2000); + } + } + + void UpdateAI(uint32 diff) override + { + events.Update(diff); + + while (uint32 eventID = events.ExecuteEvent()) + { + switch (eventID) + { + case EVENT_SCENE_1: + GetCitizenGuids(); + me->GetMotionMaster()->MoveIdle(); + if (Creature* gryshka = ObjectAccessor::GetCreature(*me, gryshkaGUID)) + { + me->SetFacingTo(me->GetAngle(gryshka->GetPositionX(), gryshka->GetPositionY())); + gryshka->AI()->Talk(SAY_GRYSHKA_1); + } + events.ScheduleEvent(EVENT_SCENE_2, 4500); + break; + case EVENT_SCENE_2: + if (Creature* olvia = ObjectAccessor::GetCreature(*me, olviaGUID)) + olvia->AI()->Talk(SAY_OLVIA_1); + events.ScheduleEvent(EVENT_SCENE_3, 4500); + break; + case EVENT_SCENE_3: + if (Creature* felika = ObjectAccessor::GetCreature(*me, felikaGUID)) + felika->AI()->Talk(SAY_FELIKA_1); + events.ScheduleEvent(EVENT_SCENE_4, 4500); + break; + case EVENT_SCENE_4: + if (Creature* thathung = ObjectAccessor::GetCreature(*me, thungGUID)) + thathung->AI()->Talk(SAY_THATHUNG); + events.ScheduleEvent(EVENT_SCENE_5, 4500); + break; + case EVENT_SCENE_5: + if (Creature* sana = ObjectAccessor::GetCreature(*me, sanaGUID)) + sana->AI()->Talk(SAY_SANA); + events.ScheduleEvent(EVENT_SCENE_6, 4500); + break; + case EVENT_SCENE_6: + if (Creature* gryshka = ObjectAccessor::GetCreature(*me, gryshkaGUID)) + gryshka->AI()->Talk(SAY_GRYSHKA_2); + events.ScheduleEvent(EVENT_SCENE_7, 4500); + break; + case EVENT_SCENE_7: + if (Creature* kaja = ObjectAccessor::GetCreature(*me, kajaGUID)) + kaja->AI()->Talk(SAY_KAJA); + events.ScheduleEvent(EVENT_SCENE_8, 4500); + break; + case EVENT_SCENE_8: + if (Creature* felika = ObjectAccessor::GetCreature(*me, felikaGUID)) + felika->AI()->Talk(SAY_FELIKA_2); + events.ScheduleEvent(EVENT_SCENE_9, 4500); + break; + case EVENT_SCENE_9: + if (Creature* olvia = ObjectAccessor::GetCreature(*me, olviaGUID)) + olvia->AI()->Talk(SAY_OLVIA_2); + events.ScheduleEvent(EVENT_SCENE_10, 4500); + break; + case EVENT_SCENE_10: + Talk(SAY_RUNTHAK_1); + events.ScheduleEvent(EVENT_SCENE_11, 1500); + break; + case EVENT_SCENE_11: + Talk(SAY_RUNTHAK_2); + events.ScheduleEvent(EVENT_SCENE_12, 4500); + break; + case EVENT_SCENE_12: + Talk(SAY_RUNTHAK_3); + events.ScheduleEvent(EVENT_SCENE_13, 4500); + break; + case EVENT_SCENE_13: + Talk(SAY_RUNTHAK_4); + events.ScheduleEvent(EVENT_RESET, 25000); + break; + case EVENT_RESET: + Reset(); + break; + default: + break; + } + } + } + + void GetCitizenGuids() + { + // if one GUID is empty it means all the others are empty as well so we should store them + // otherwise do not call for grid search since someone else already activated event once before and guids are stored + if (gryshkaGUID.IsEmpty()) + { + std::list<Unit*> citizenList; + Trinity::AnyFriendlyUnitInObjectRangeCheck checker(me, me, 25.0f); + Trinity::UnitListSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(me, citizenList, checker); + me->VisitNearbyObject(20.0f, searcher); + for (Unit* target : citizenList) + { + switch (target->GetEntry()) + { + case NPC_GRYSHKA: + gryshkaGUID = target->GetGUID(); + break; + case NPC_OLVIA: + olviaGUID = target->GetGUID(); + break; + case NPC_SANA: + sanaGUID = target->GetGUID(); + break; + case NPC_FELIKA: + felikaGUID = target->GetGUID(); + break; + case NPC_THATHUNG: + thungGUID = target->GetGUID(); + break; + case NPC_KAJA: + kajaGUID = target->GetGUID(); + break; + default: + break; + } + } + } + } + + private: + EventMap events; + bool inProgress; + ObjectGuid gryshkaGUID; + ObjectGuid olviaGUID; + ObjectGuid sanaGUID; + ObjectGuid felikaGUID; + ObjectGuid thungGUID; + ObjectGuid kajaGUID; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_overlord_runthak_orgrimmarAI(creature); + } +}; + +// Phased out thrall during herald of war chain quest +enum HeraldEntries +{ + NPC_PORTAL_STORMWIND = 31640, + NPC_JAINA_PROUDMOORE = 31418, + NPC_BANSHEE_SYLVANAS = 31419, + NPC_KORKRON_GUARD = 31417, + NPC_THRALL_HERALD = 31412, + + GO_PORTAL_UNDERCITY = 193425 +}; + +enum HeraldMisc +{ + QUEST_HERALD_OF_WAR = 13257, + GUARDS_SIZE = 4 +}; + +enum HeraldActions +{ + ACTION_START_SCENE = 0 +}; + +enum HeraldSpell +{ + SPELL_JAINA_SPAWNIN = 55761 +}; + +enum HeraldTalk +{ + SAY_THRALL_0 = 0, // Kor'kron, stand down! + SAY_THRALL_1 = 1, // Jaina... + SAY_THRALL_2 = 2, // Jaina, what happened at the Wrathgate. It was a betrayal from within... + SAY_THRALL_3 = 3, // The Horde has lost the Undercity. + SAY_THRALL_4 = 4, // We now prepare to lay siege to the city and bring the perpetrators of this unforgivable crime to justice. + SAY_THRALL_5 = 5, // If we are forced into a conflict, the Lich King will destroy our divided forces in Northrend. + SAY_THRALL_6 = 6, // We will make this right, Jaina. Tell your king all that you have learned here. + SAY_THRALL_7 = 7, // Kor'kron, prepare transport to the Undercity. + + SAY_SYLVANAS_0 = 0, // Lady Proudmoore, the Warchief speaks the truth. This subterfuge was set in motion by Varimathras and Grand Apothecary Putress. It was not the Horde's doing. + SAY_SYLVANAS_1 = 1, // As the combined Horde and Alliance forces began their assault upon the Wrath Gate, an uprising broke out in the Undercity. Varimathras and hordes of his demonic brethren attacked. Hundreds of my people were slain in the coup. I barely managed to escape with my life. + + SAY_JAINA_0 = 0, // Thrall, what has happened? The King is preparing for war... + SAY_JAINA_1 = 1, // I will deliver this information to King Wrynn, Thrall, but... + SAY_JAINA_2 = 2, // Bolvar was like a brother to him. In the King's absence, Bolvar kept the Alliance united. He found strength for our people in our darkest hours. He watched over Anduin, raising him as his own. + SAY_JAINA_3 = 3, // I fear that the rage will consume him, Thrall. I remain hopeful that reason will prevail, but we must prepare for the worst... for war. + SAY_JAINA_4 = 4 // Farewell, Warchief. I pray that the next time we meet it will be as allies. +}; + +enum HeraldEvents +{ + EVENT_HERALD_SCENE1 = 1, + EVENT_HERALD_SCENE2 = 2, + EVENT_HERALD_SCENE3 = 3, + EVENT_HERALD_SCENE4 = 4, + EVENT_HERALD_SCENE5 = 5, + EVENT_HERALD_SCENE6 = 6, + EVENT_HERALD_SCENE7 = 7, + EVENT_HERALD_SCENE8 = 8, + EVENT_HERALD_SCENE9 = 9, + EVENT_HERALD_SCENE10 = 10, + EVENT_HERALD_SCENE11 = 11, + EVENT_HERALD_SCENE12 = 12, + EVENT_HERALD_SCENE13 = 13, + EVENT_HERALD_SCENE14 = 14, + EVENT_HERALD_SCENE15 = 15, + EVENT_HERALD_RESET = 16 +}; + +Position const GuardsSpawnPosition[GUARDS_SIZE] = +{ + { 1909.39f, -4144.21f, 40.6368f, 0.042239f }, + { 1910.73f, -4155.26f, 40.6316f, 0.615577f }, + { 1934.01f, -4141.40f, 40.6375f, 3.61109f }, + { 1931.11f, -4156.38f, 40.6130f, 2.19737f } +}; + +Position const GuardsMovePosition[GUARDS_SIZE] = +{ + { 1917.461670f, -4147.514160f, 40.636799f, 5.89346f }, + { 1916.181274f, -4152.295898f, 40.629120f, 0.497757f }, + { 1926.435425f, -4146.397461f, 40.618534f, 3.846709f }, + { 1926.519165f, -4153.216797f, 40.614975f, 2.570434f } +}; + +Position const MiscMovePositions[3] = +{ + { 1921.719604f, -4143.051270f, 40.623356f, 1.657789f }, // jaina move + { 1921.151855f, -4139.343750f, 40.583084f, 4.732627f }, // thrall move + { 1918.732422f, -4139.619629f, 40.607685f, 4.803311f } // sylvanas move +}; + +Position const PortalSpawnPosition = { 1921.752441f, -4151.148438f, 40.623848f, 1.714324f }; + +class npc_thrall_herald_of_war : public CreatureScript +{ +public: + npc_thrall_herald_of_war() : CreatureScript("npc_thrall_herald_of_war") { } + + struct npc_thrall_herald_of_warAI : public ScriptedAI + { + npc_thrall_herald_of_warAI(Creature* creature) : ScriptedAI(creature) + { + spawnedGuards = false; + sceneInProgress = false; + } + + void Reset() override + { + events.Reset(); + me->GetMotionMaster()->MovePath(me->GetSpawnId() * 10, true); + sceneInProgress = false; + + if (!spawnedGuards) + { + spawnedGuards = true; + for (uint8 i = 0; i < GUARDS_SIZE; i++) + { + if (Creature* korkronGuard = me->SummonCreature(NPC_KORKRON_GUARD, GuardsSpawnPosition[i])) + guardsGUIDs[i] = korkronGuard->GetGUID(); + } + } + } + + void MovementInform(uint32 type, uint32 pointId) override + { + if (type != POINT_MOTION_TYPE) + return; + + if (pointId == 2) + me->GetMotionMaster()->MovePath(me->GetSpawnId() * 10, true); + } + + void DoAction(int32 actionId) override + { + if (actionId == ACTION_START_SCENE && !sceneInProgress) + { + me->GetMotionMaster()->MoveIdle(); + sceneInProgress = true; + + if (Creature* jaina = me->SummonCreature(NPC_JAINA_PROUDMOORE, PortalSpawnPosition)) + { + me->SetFacingTo(me->GetAngle(jaina->GetPositionX(), jaina->GetPositionY())); + jainaGUID = jaina->GetGUID(); + jaina->CastSpell(jaina, SPELL_JAINA_SPAWNIN); + } + + if (Creature* stormwindPortal = me->SummonCreature(NPC_PORTAL_STORMWIND, PortalSpawnPosition)) + { + stormwindPortal->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + stormwindPortalGUID = stormwindPortal->GetGUID(); + } + + for (uint8 i = 0; i < GUARDS_SIZE; i++) + { + if (Creature* guards = ObjectAccessor::GetCreature(*me, guardsGUIDs[i])) + { + guards->SetWalk(false); + guards->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_READY2H); + guards->GetMotionMaster()->MovePoint(1, GuardsMovePosition[i]); + } + } + + if (Creature* sylvanas = me->FindNearestCreature(NPC_BANSHEE_SYLVANAS, 25.0f)) + sylvanasGUID = sylvanas->GetGUID(); + + events.ScheduleEvent(EVENT_HERALD_SCENE1, 4000); + } + } + + void UpdateAI(uint32 diff) override + { + events.Update(diff); + + while (uint32 eventID = events.ExecuteEvent()) + { + switch (eventID) + { + case EVENT_HERALD_SCENE1: + Talk(SAY_THRALL_0); + me->GetMotionMaster()->MovePoint(1, MiscMovePositions[1]); + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + { + jaina->SetWalk(true); + jaina->GetMotionMaster()->MovePoint(1, MiscMovePositions[0]); + } + + for (uint8 i = 0; i < GUARDS_SIZE; i++) + { + if (Creature* guard = ObjectAccessor::GetCreature(*me, guardsGUIDs[i])) + { + guard->GetMotionMaster()->MoveTargetedHome(); + guard->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); + } + } + events.ScheduleEvent(EVENT_HERALD_SCENE2, 3000); + break; + case EVENT_HERALD_SCENE2: + Talk(SAY_THRALL_1); + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + me->SetFacingTo(me->GetAngle(jaina->GetPositionX(), jaina->GetPositionY())); + events.ScheduleEvent(EVENT_HERALD_SCENE3, 3500); + break; + case EVENT_HERALD_SCENE3: + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + jaina->AI()->Talk(SAY_JAINA_0); + events.ScheduleEvent(EVENT_HERALD_SCENE4, 5500); + break; + case EVENT_HERALD_SCENE4: + Talk(SAY_THRALL_2); + if (Creature* sylvanas = ObjectAccessor::GetCreature(*me, sylvanasGUID)) + { + sylvanas->SetStandState(UNIT_STAND_STATE_STAND); + sylvanas->SetWalk(true); + sylvanas->GetMotionMaster()->MovePoint(1, MiscMovePositions[2]); + } + events.ScheduleEvent(EVENT_HERALD_SCENE5, 6500); + break; + case EVENT_HERALD_SCENE5: + if (Creature* sylvanas = ObjectAccessor::GetCreature(*me, sylvanasGUID)) + sylvanas->AI()->Talk(SAY_SYLVANAS_0); + events.ScheduleEvent(EVENT_HERALD_SCENE6, 10000); + break; + case EVENT_HERALD_SCENE6: + if (Creature* sylvanas = ObjectAccessor::GetCreature(*me, sylvanasGUID)) + sylvanas->AI()->Talk(SAY_SYLVANAS_1); + events.ScheduleEvent(EVENT_HERALD_SCENE7, 20000); + break; + case EVENT_HERALD_SCENE7: + Talk(SAY_THRALL_3); + events.ScheduleEvent(EVENT_HERALD_SCENE8, 4500); + break; + case EVENT_HERALD_SCENE8: + Talk(SAY_THRALL_4); + events.ScheduleEvent(EVENT_HERALD_SCENE9, 10000); + break; + case EVENT_HERALD_SCENE9: + Talk(SAY_THRALL_5); + events.ScheduleEvent(EVENT_HERALD_SCENE10, 8000); + break; + case EVENT_HERALD_SCENE10: + Talk(SAY_THRALL_6); + events.ScheduleEvent(EVENT_HERALD_SCENE11, 9000); + break; + case EVENT_HERALD_SCENE11: + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + jaina->AI()->Talk(SAY_JAINA_1); + events.ScheduleEvent(EVENT_HERALD_SCENE12, 6000); + break; + case EVENT_HERALD_SCENE12: + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + jaina->AI()->Talk(SAY_JAINA_2); + events.ScheduleEvent(EVENT_HERALD_SCENE13, 14000); + break; + case EVENT_HERALD_SCENE13: + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + jaina->AI()->Talk(SAY_JAINA_3); + events.ScheduleEvent(EVENT_HERALD_SCENE14, 10000); + break; + case EVENT_HERALD_SCENE14: + if (Creature* jaina = ObjectAccessor::GetCreature(*me, jainaGUID)) + { + jaina->AI()->Talk(SAY_JAINA_4); + jaina->SetWalk(true); + jaina->GetMotionMaster()->MovePoint(2, jaina->GetHomePosition()); + jaina->DespawnOrUnsummon(5000); + } + events.ScheduleEvent(EVENT_HERALD_SCENE15, 7000); + break; + case EVENT_HERALD_SCENE15: + { + me->SetWalk(true); + me->GetMotionMaster()->MovePoint(2, me->GetHomePosition()); + Talk(SAY_THRALL_7); + + if (Creature* sylvanas = ObjectAccessor::GetCreature(*me, sylvanasGUID)) + { + sylvanas->SetWalk(true); + sylvanas->GetMotionMaster()->MovePoint(2, sylvanas->GetHomePosition()); + } + + if (Creature* portal = ObjectAccessor::GetCreature(*me, stormwindPortalGUID)) + portal->DespawnOrUnsummon(); + + events.ScheduleEvent(EVENT_HERALD_RESET, 60000); + break; + } + case EVENT_HERALD_RESET: + Reset(); + break; + default: + break; + } + } + } + + private: + EventMap events; + ObjectGuid guardsGUIDs[GUARDS_SIZE]; + ObjectGuid jainaGUID; + ObjectGuid sylvanasGUID; + ObjectGuid stormwindPortalGUID; + bool spawnedGuards; + bool sceneInProgress; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_thrall_herald_of_warAI(creature); + } +}; + +class areatrigger_orgrimmar_herald_of_war : public AreaTriggerScript +{ +public: + areatrigger_orgrimmar_herald_of_war() : AreaTriggerScript("areatrigger_orgrimmar_herald_of_war") { } + + bool OnTrigger(Player* player, AreaTriggerEntry const* /*trigger*/) override + { + if (player->IsAlive() && player->GetQuestStatus(QUEST_HERALD_OF_WAR) == QUEST_STATUS_COMPLETE) + { + if (Creature* thrall = player->FindNearestCreature(NPC_THRALL_HERALD, 50.0f)) + { + thrall->AI()->DoAction(ACTION_START_SCENE); + return true; + } + } + return false; + } +}; + void AddSC_orgrimmar() { new npc_shenthul(); new npc_thrall_warchief(); + new npc_overlord_runthak_orgrimmar(); + new npc_thrall_herald_of_war(); + new areatrigger_orgrimmar_herald_of_war(); } diff --git a/src/server/scripts/Kalimdor/zone_silithus.cpp b/src/server/scripts/Kalimdor/zone_silithus.cpp index cc285ab991e..db7bd62c5d1 100644 --- a/src/server/scripts/Kalimdor/zone_silithus.cpp +++ b/src/server/scripts/Kalimdor/zone_silithus.cpp @@ -19,13 +19,20 @@ /* ScriptData SDName: Silithus SD%Complete: 100 -SDComment: Quest support: 8304, 8507. +SDComment: Quest support: 8348,8352,8361,8519 SDCategory: Silithus EndScriptData */ /* ContentData -npcs_rutgar_and_frankal -quest_a_pawn_on_the_eternal_pawn +A Pawn on the Eternal Board - creatures, gameobjects and defines +quest_a_pawn_on_the_eternal_board +npc_qiraj_war_spawn : Adds that are summoned in the Qiraj gates battle. +npc_anachronos_the_ancient : Creature that controls the event. +npc_anachronos_quest_trigger: controls the spawning of the BG War mobs. +go_crystalline_tear : GameObject that begins the event and hands out quest +TO DO: get correct spell IDs and timings for spells cast upon dragon transformations +TO DO: Dragons should use the HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF) after transformation, + but for some unknown reason it doesn't work. EndContentData */ #include "ScriptMgr.h" @@ -34,195 +41,66 @@ EndContentData */ #include "Group.h" #include "Player.h" -/*### -## npcs_rutgar_and_frankal -###*/ - -//gossip item text best guess -#define GOSSIP_ITEM1 "I seek information about Natalia" - -#define GOSSIP_ITEM2 "That sounds dangerous!" -#define GOSSIP_ITEM3 "What did you do?" -#define GOSSIP_ITEM4 "Who?" -#define GOSSIP_ITEM5 "Women do that. What did she demand?" -#define GOSSIP_ITEM6 "What do you mean?" -#define GOSSIP_ITEM7 "What happened next?" - -#define GOSSIP_ITEM11 "Yes, please continue" -#define GOSSIP_ITEM12 "What language?" -#define GOSSIP_ITEM13 "The Priestess attacked you?!" -#define GOSSIP_ITEM14 "I should ask the monkey about this" -#define GOSSIP_ITEM15 "Then what..." - -enum RutgarAndFrankal //trigger creatures to kill -{ - TRIGGER_FRANKAL = 15221, - TRIGGER_RUTGAR = 15222 -}; - -class npcs_rutgar_and_frankal : public CreatureScript -{ -public: - npcs_rutgar_and_frankal() : CreatureScript("npcs_rutgar_and_frankal") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->SEND_GOSSIP_MENU(7755, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->SEND_GOSSIP_MENU(7756, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->SEND_GOSSIP_MENU(7757, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - player->SEND_GOSSIP_MENU(7758, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); - player->SEND_GOSSIP_MENU(7759, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM7, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); - player->SEND_GOSSIP_MENU(7760, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 6: - player->SEND_GOSSIP_MENU(7761, creature->GetGUID()); - //'kill' our trigger to update quest status - player->KilledMonsterCredit(TRIGGER_RUTGAR); - break; - - case GOSSIP_ACTION_INFO_DEF + 9: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM11, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); - player->SEND_GOSSIP_MENU(7762, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 10: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM12, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); - player->SEND_GOSSIP_MENU(7763, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 11: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM13, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 12); - player->SEND_GOSSIP_MENU(7764, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 12: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM14, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 13); - player->SEND_GOSSIP_MENU(7765, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 13: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM15, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 14); - player->SEND_GOSSIP_MENU(7766, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF + 14: - player->SEND_GOSSIP_MENU(7767, creature->GetGUID()); - //'kill' our trigger to update quest status - player->KilledMonsterCredit(TRIGGER_FRANKAL); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(8304) == QUEST_STATUS_INCOMPLETE && - creature->GetEntry() == 15170 && - !player->GetReqKillOrCastCurrentCount(8304, TRIGGER_RUTGAR)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - - if (player->GetQuestStatus(8304) == QUEST_STATUS_INCOMPLETE && - creature->GetEntry() == 15171 && - player->GetReqKillOrCastCurrentCount(8304, TRIGGER_RUTGAR)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+9); - - player->SEND_GOSSIP_MENU(7754, creature->GetGUID()); - - return true; - } - -}; - -/*#### -# quest_a_pawn_on_the_eternal_board (Defines) -####*/ -enum EternalBoard -{ - QUEST_A_PAWN_ON_THE_ETERNAL_BOARD = 8519, - - FACTION_HOSTILE = 14, - FACTION_FRIENDLY = 35, - - C_ANACHRONOS = 15381, - C_FANDRAL_STAGHELM = 15382, - C_ARYGOS = 15380, - C_MERITHRA = 15378, - C_CAELESTRASZ = 15379, - - ANACHRONOS_SAY_1 = 0, - ANACHRONOS_SAY_2 = 1, - ANACHRONOS_SAY_3 = 2, - ANACHRONOS_SAY_4 = 3, - ANACHRONOS_SAY_5 = 4, - ANACHRONOS_SAY_6 = 5, - ANACHRONOS_SAY_7 = 6, - ANACHRONOS_SAY_8 = 7, - ANACHRONOS_SAY_9 = 8, - ANACHRONOS_SAY_10 = 9, - ANACHRONOS_EMOTE_1 = 10, - ANACHRONOS_EMOTE_2 = 11, - ANACHRONOS_EMOTE_3 = 12, - - FANDRAL_SAY_1 = 0, - FANDRAL_SAY_2 = 1, - FANDRAL_SAY_3 = 2, - FANDRAL_SAY_4 = 3, - FANDRAL_SAY_5 = 4, - FANDRAL_SAY_6 = 5, - FANDRAL_EMOTE_1 = 6, - FANDRAL_EMOTE_2 = 7, - - CAELESTRASZ_SAY_1 = 0, - CAELESTRASZ_SAY_2 = 1, - CAELESTRASZ_YELL_1 = 2, - - ARYGOS_SAY_1 = 0, - ARYGOS_YELL_1 = 1, - ARYGOS_EMOTE_1 = 2, - - MERITHRA_SAY_1 = 0, - MERITHRA_SAY_2 = 1, - MERITHRA_YELL_1 = 2, - MERITHRA_EMOTE_1 = 3, - - GO_GATE_OF_AHN_QIRAJ = 176146, - GO_GLYPH_OF_AHN_QIRAJ = 176148, - GO_ROOTS_OF_AHN_QIRAJ = 176147 -}; /*##### # Quest: A Pawn on the Eternal Board #####*/ -/* ContentData -A Pawn on the Eternal Board - creatures, gameobjects and defines -npc_qiraj_war_spawn : Adds that are summoned in the Qiraj gates battle. -npc_anachronos_the_ancient : Creature that controls the event. -npc_anachronos_quest_trigger: controls the spawning of the BG War mobs. -go_crystalline_tear : GameObject that begins the event and hands out quest -TO DO: get correct spell IDs and timings for spells cast upon dragon transformations -TO DO: Dragons should use the HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF) after transformation, but for some unknown reason it doesnt work. -EndContentData */ - -#define EVENT_AREA_RADIUS 65 //65yds -#define EVENT_COOLDOWN 500000 //in ms. appear after event completed or failed (should be = Adds despawn time) +enum EternalBoard +{ + QUEST_A_PAWN_ON_THE_ETERNAL_BOARD = 8519, + + FACTION_HOSTILE = 14, + FACTION_FRIENDLY = 35, + + EVENT_AREA_RADIUS = 65, // 65yds + EVENT_COOLDOWN = 500000, // in ms. appears after event completed or failed (should be = Adds despawn time) + + NPC_ANACHRONOS = 15381, + NPC_FANDRAL_STAGHELM = 15382, + NPC_ARYGOS = 15380, + NPC_MERITHRA_OF_THE_DREAM = 15378, + NPC_CAELESTRASZ = 15379, + + ANACHRONOS_SAY_1 = 0, + ANACHRONOS_SAY_2 = 1, + ANACHRONOS_SAY_3 = 2, + ANACHRONOS_SAY_4 = 3, + ANACHRONOS_SAY_5 = 4, + ANACHRONOS_SAY_6 = 5, + ANACHRONOS_SAY_7 = 6, + ANACHRONOS_SAY_8 = 7, + ANACHRONOS_SAY_9 = 8, + ANACHRONOS_SAY_10 = 9, + ANACHRONOS_EMOTE_1 = 10, + ANACHRONOS_EMOTE_2 = 11, + ANACHRONOS_EMOTE_3 = 12, + + FANDRAL_SAY_1 = 0, + FANDRAL_SAY_2 = 1, + FANDRAL_SAY_3 = 2, + FANDRAL_SAY_4 = 3, + FANDRAL_SAY_5 = 4, + FANDRAL_SAY_6 = 5, + FANDRAL_EMOTE_1 = 6, + FANDRAL_EMOTE_2 = 7, + + CAELESTRASZ_SAY_1 = 0, + CAELESTRASZ_SAY_2 = 1, + CAELESTRASZ_YELL_1 = 2, + + ARYGOS_SAY_1 = 0, + ARYGOS_YELL_1 = 1, + ARYGOS_EMOTE_1 = 2, + + MERITHRA_SAY_1 = 0, + MERITHRA_SAY_2 = 1, + MERITHRA_YELL_1 = 2, + MERITHRA_EMOTE_1 = 3, + + GO_GATE_OF_AHN_QIRAJ = 176146, + GO_GLYPH_OF_AHN_QIRAJ = 176148, + GO_ROOTS_OF_AHN_QIRAJ = 176147 +}; struct QuestCinematic { @@ -233,59 +111,59 @@ struct QuestCinematic // Creature 0 - Anachronos, 1 - Fandral, 2 - Arygos, 3 - Merithra, 4 - Caelestrasz static QuestCinematic EventAnim[]= { - {ANACHRONOS_SAY_1, 0, 2000}, - {FANDRAL_SAY_1, 1, 4000}, - {MERITHRA_EMOTE_1, 3, 500}, - {MERITHRA_SAY_1, 3, 500}, - {ARYGOS_EMOTE_1, 2, 2000}, + {ANACHRONOS_SAY_1, 0, 2000}, + {FANDRAL_SAY_1, 1, 4000}, + {MERITHRA_EMOTE_1, 3, 500}, + {MERITHRA_SAY_1, 3, 500}, + {ARYGOS_EMOTE_1, 2, 2000}, {CAELESTRASZ_SAY_1, 4, 8000}, - {MERITHRA_SAY_2, 3, 6000}, + {MERITHRA_SAY_2, 3, 6000}, {0, 3, 2000}, - {MERITHRA_YELL_1, 3, 2500}, - {0, 3, 3000}, //Morph - {0, 3, 4000}, //EmoteLiftoff - {0, 3, 4000}, // spell - {0, 3, 1250}, //fly - {0, 3, 250}, //remove flags + {MERITHRA_YELL_1, 3, 2500}, + {0, 3, 3000}, //Morph + {0, 3, 4000}, //EmoteLiftoff + {0, 3, 4000}, // spell + {0, 3, 1250}, //fly + {0, 3, 250}, //remove flags {ARYGOS_SAY_1, 2, 3000}, {0, 3, 2000}, {ARYGOS_YELL_1, 2, 3000}, - {0, 3, 3000}, //Morph - {0, 3, 4000}, //EmoteLiftoff - {0, 3, 4000}, // spell - {0, 3, 1000}, //fly - {0, 3, 1000}, //remove flags + {0, 3, 3000}, //Morph + {0, 3, 4000}, //EmoteLiftoff + {0, 3, 4000}, // spell + {0, 3, 1000}, //fly + {0, 3, 1000}, //remove flags {CAELESTRASZ_SAY_2, 4, 5000}, {0, 3, 3000}, {CAELESTRASZ_YELL_1, 4, 3000}, - {0, 3, 3000}, //Morph - {0, 3, 4000}, //EmoteLiftoff - {0, 3, 2500}, // spell + {0, 3, 3000}, //Morph + {0, 3, 4000}, //EmoteLiftoff + {0, 3, 2500}, // spell {ANACHRONOS_SAY_2, 0, 2000}, - {0, 3, 250}, //fly - {0, 3, 25}, //remove flags + {0, 3, 250}, //fly + {0, 3, 25}, //remove flags {FANDRAL_SAY_2, 1, 3000}, - {ANACHRONOS_SAY_3, 0, 10000}, //Both run through the armies - {0, 3, 2000}, // Sands will stop - {0, 3, 8000}, // Summon Gate + {ANACHRONOS_SAY_3, 0, 10000}, //Both run through the armies + {0, 3, 2000}, // Sands will stop + {0, 3, 8000}, // Summon Gate {ANACHRONOS_SAY_4, 0, 4000}, - {0, 0, 2000}, //spell 1-> Arcane cosmetic (Mobs freeze) - {0, 0, 5000}, //Spell 2-> Arcane long cosmetic (barrier appears) (Barrier -> Glyphs) - {0, 0, 7000}, //BarrieR - {0, 0, 4000}, //Glyphs + {0, 0, 2000}, //spell 1-> Arcane cosmetic (Mobs freeze) + {0, 0, 5000}, //Spell 2-> Arcane long cosmetic (barrier appears) (Barrier -> Glyphs) + {0, 0, 7000}, //BarrieR + {0, 0, 4000}, //Glyphs {ANACHRONOS_SAY_5, 0, 2000}, - {0, 0, 4000}, // Roots - {FANDRAL_SAY_3, 1, 3000}, //Root Text - {FANDRAL_EMOTE_1, 1, 3000}, //falls knee + {0, 0, 4000}, // Roots + {FANDRAL_SAY_3, 1, 3000}, //Root Text + {FANDRAL_EMOTE_1, 1, 3000}, //falls knee {ANACHRONOS_SAY_6, 0, 3000}, {ANACHRONOS_SAY_7, 0, 3000}, {ANACHRONOS_SAY_8, 0, 8000}, - {ANACHRONOS_EMOTE_1, 0, 1000}, //Give Scepter + {ANACHRONOS_EMOTE_1, 0, 1000}, //Give Scepter {FANDRAL_SAY_4, 1, 3000}, - {FANDRAL_SAY_5, 1, 3000}, //->Equip hammer~Scepter, throw it at door - {FANDRAL_EMOTE_2, 1, 3000}, //Throw hammer at door. + {FANDRAL_SAY_5, 1, 3000}, //->Equip hammer~Scepter, throw it at door + {FANDRAL_EMOTE_2, 1, 3000}, //Throw hammer at door. {ANACHRONOS_SAY_9, 0, 3000}, - {FANDRAL_SAY_6, 1, 3000}, //fandral goes away + {FANDRAL_SAY_6, 1, 3000}, //fandral goes away {ANACHRONOS_EMOTE_2, 0, 3000}, {ANACHRONOS_EMOTE_3, 0, 3000}, {0, 0, 2000}, @@ -348,30 +226,30 @@ Position const SpawnLocation[] = {-8078.0f, 1518.0f, 2.61f, 3.141592f}, //Kaldorei Infantry {-8082.0f, 1516.0f, 2.61f, 3.141592f}, //Kaldorei Infantry - {-8088.0f, 1510.0f, 2.61f, 0.0f}, //Anubisath Conqueror - {-8084.0f, 1520.0f, 2.61f, 0.0f}, //Anubisath Conqueror - {-8088.0f, 1530.0f, 2.61f, 0.0f}, //Anubisath Conqueror - - {-8080.0f, 1513.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8082.0f, 1523.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8085.0f, 1518.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8082.0f, 1516.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8085.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8080.0f, 1528.0f, 2.61f, 0.0f}, //Qiraj Wasp - - {-8082.0f, 1513.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8079.0f, 1523.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8080.0f, 1531.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8079.0f, 1516.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8082.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Wasp - {-8080.0f, 1518.0f, 2.61f, 0.0f}, //Qiraj Wasp - - {-8081.0f, 1514.0f, 2.61f, 0.0f}, //Qiraj Tank - {-8081.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Tank - {-8081.0f, 1526.0f, 2.61f, 0.0f}, //Qiraj Tank - {-8081.0f, 1512.0f, 2.61f, 0.0f}, //Qiraj Tank - {-8082.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Tank - {-8081.0f, 1528.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8088.0f, 1510.0f, 2.61f, 0.0f}, //Anubisath Conqueror + {-8084.0f, 1520.0f, 2.61f, 0.0f}, //Anubisath Conqueror + {-8088.0f, 1530.0f, 2.61f, 0.0f}, //Anubisath Conqueror + + {-8080.0f, 1513.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8082.0f, 1523.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8085.0f, 1518.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8082.0f, 1516.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8085.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8080.0f, 1528.0f, 2.61f, 0.0f}, //Qiraj Wasp + + {-8082.0f, 1513.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8079.0f, 1523.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8080.0f, 1531.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8079.0f, 1516.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8082.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Wasp + {-8080.0f, 1518.0f, 2.61f, 0.0f}, //Qiraj Wasp + + {-8081.0f, 1514.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8081.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8081.0f, 1526.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8081.0f, 1512.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8082.0f, 1520.0f, 2.61f, 0.0f}, //Qiraj Tank + {-8081.0f, 1528.0f, 2.61f, 0.0f}, //Qiraj Tank {-8082.0f, 1513.0f, 2.61f, 3.141592f}, //Anubisath Conqueror {-8082.0f, 1520.0f, 2.61f, 3.141592f}, //Anubisath Conqueror @@ -402,14 +280,36 @@ struct SpawnSpells static SpawnSpells SpawnCast[4] = { - {100000, 2000, 33652}, // Stop Time + {100000, 2000, 33652}, // Stoned {38500, 300000, 28528}, // Poison Cloud {58000, 300000, 35871}, // Frost Debuff (need correct spell) {80950, 300000, 42075}, // Fire Explosion (need correct spell however this one looks cool) }; + /*##### # npc_anachronos_the_ancient ######*/ + +enum AnachronosTheAncient +{ + NPC_QIRAJI_WASP = 15414, + NPC_QIRAJI_TANK = 15422, + NPC_KALDOREI_INFANTRY = 15423, + NPC_ANUBISATH_CONQUEROR = 15424, + SPELL_ARCANE_CHANNELING = 23017, + SPELL_NOXIOUS_BREATH = 24818, + SPELL_GREEN_DRAGON_TRANSFORM_DND = 25105, + SPELL_RED_DRAGON_TRANSFORM_DND = 25106, + SPELL_BLUE_DRAGON_TRANSFORM_DND = 25107, + SPELL_TIME_STOP = 25158, + SPELL_CALL_PRISMATIC_BARRIER = 25159, + SPELL_CALL_GLYPHS_OF_WARDING = 25166, + SPELL_CALL_ANCIENTS = 25167, + SPELL_THROW_HAMMER = 33806, + SPELL_FROST_BREATH = 50505, + SPELL_FLAME_BREATH = 54293 +}; + class npc_anachronos_the_ancient : public CreatureScript { public: @@ -464,10 +364,10 @@ public: if (!player) return; - Creature* Fandral = player->FindNearestCreature(C_FANDRAL_STAGHELM, 100.0f); - Creature* Arygos = player->FindNearestCreature(C_ARYGOS, 100.0f); - Creature* Caelestrasz = player->FindNearestCreature(C_CAELESTRASZ, 100.0f); - Creature* Merithra = player->FindNearestCreature(C_MERITHRA, 100.0f); + Creature* Fandral = player->FindNearestCreature(NPC_FANDRAL_STAGHELM, 100.0f); + Creature* Arygos = player->FindNearestCreature(NPC_ARYGOS, 100.0f); + Creature* Caelestrasz = player->FindNearestCreature(NPC_CAELESTRASZ, 100.0f); + Creature* Merithra = player->FindNearestCreature(NPC_MERITHRA_OF_THE_DREAM, 100.0f); if (!Fandral || !Arygos || !Caelestrasz || !Merithra) return; @@ -509,7 +409,7 @@ public: Merithra->AI()->Talk(MERITHRA_YELL_1); break; case 9: - Merithra->CastSpell(Merithra, 25105, true); + Merithra->CastSpell(Merithra, SPELL_GREEN_DRAGON_TRANSFORM_DND, true); break; case 10: Merithra->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); @@ -517,7 +417,7 @@ public: Merithra->GetMotionMaster()->MoveCharge(-8065, 1530, 6.61f, 3); break; case 11: - Merithra->CastSpell(Merithra, 24818, false); + Merithra->CastSpell(Merithra, SPELL_NOXIOUS_BREATH, false); break; case 12: Merithra->GetMotionMaster()->MoveCharge(-8100, 1530, 50, 42); @@ -536,7 +436,7 @@ public: Arygos->AI()->Talk(ARYGOS_YELL_1); break; case 17: - Arygos->CastSpell(Arygos, 25107, true); + Arygos->CastSpell(Arygos, SPELL_BLUE_DRAGON_TRANSFORM_DND, true); break; case 18: Arygos->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); @@ -544,7 +444,7 @@ public: Arygos->GetMotionMaster()->MoveCharge(-8065, 1530, 6.61f, 42); break; case 19: - Arygos->CastSpell(Arygos, 50505, false); + Arygos->CastSpell(Arygos, SPELL_FROST_BREATH, false); break; case 20: Arygos->GetMotionMaster()->MoveCharge(-8095, 1530, 50, 42); @@ -563,15 +463,15 @@ public: Caelestrasz->AI()->Talk(CAELESTRASZ_YELL_1); break; case 25: - Caelestrasz->CastSpell(Caelestrasz, 25106, true); + Caelestrasz->CastSpell(Caelestrasz, SPELL_RED_DRAGON_TRANSFORM_DND, true); break; case 26: - Caelestrasz->HandleEmoteCommand(254); + Caelestrasz->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); Caelestrasz->SetDisableGravity(true); Caelestrasz->GetMotionMaster()->MoveCharge(-8065, 1530, 7.61f, 4); break; case 27: - Caelestrasz->CastSpell(Caelestrasz, 54293, false); + Caelestrasz->CastSpell(Caelestrasz, SPELL_FLAME_BREATH, false); break; case 28: Talk(ANACHRONOS_SAY_2, Fandral); @@ -596,29 +496,29 @@ public: Caelestrasz->GetMotionMaster()->MoveCharge(-8050, 1473, 65, 15); break; //Text: sands will stop case 34: - DoCast(player, 23017, true);//Arcane Channeling + DoCast(player, SPELL_ARCANE_CHANNELING, true);//Arcane Channeling break; case 35: - me->CastSpell(-8088, 1520.43f, 2.67f, 25158, true); + me->CastSpell(-8088, 1520.43f, 2.67f, SPELL_TIME_STOP, true); break; case 36: - DoCast(player, 25159, true); + DoCast(player, SPELL_CALL_PRISMATIC_BARRIER, true); break; case 37: - me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, -8130, 1525, 17.5f, 0, 0, 0, 0, 0, 0); + me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); break; case 38: - DoCast(player, 25166, true); - me->SummonGameObject(GO_GLYPH_OF_AHN_QIRAJ, -8130, 1525, 17.5f, 0, 0, 0, 0, 0, 0); + DoCast(player, SPELL_CALL_GLYPHS_OF_WARDING, true); + me->SummonGameObject(GO_GLYPH_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); break; case 39: Talk(ANACHRONOS_SAY_5, Fandral); break; case 40: - Fandral->CastSpell(me, 25167, true); + Fandral->CastSpell(me, SPELL_CALL_ANCIENTS, true); break; case 41: - Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, -8130, 1525, 17.5f, 0, 0, 0, 0, 0, 0); + Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); Fandral->AI()->Talk(FANDRAL_SAY_3); break; case 42: @@ -649,11 +549,11 @@ public: break; case 50: Fandral->AI()->Talk(FANDRAL_EMOTE_2); - Fandral->CastSpell(-8127, 1525, 17.5f, 33806, true); + Fandral->CastSpell(-8127, 1525, 17.5f, SPELL_THROW_HAMMER, true); break; case 51: { - uint32 entries[4] = { 15423, 15424, 15414, 15422 }; + uint32 entries[4] = { NPC_KALDOREI_INFANTRY, NPC_ANUBISATH_CONQUEROR, NPC_QIRAJI_WASP, NPC_QIRAJI_TANK }; Unit* mob = NULL; for (uint8 i = 0; i < 4; ++i) { @@ -661,7 +561,7 @@ public: while (mob) { mob->RemoveFromWorld(); - mob = player->FindNearestCreature(15423, 50); + mob = player->FindNearestCreature(NPC_KALDOREI_INFANTRY, 50); } } break; @@ -706,7 +606,7 @@ public: me->SetDisplayId(15500); break; case 63: - me->HandleEmoteCommand(254); + me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); me->SetDisableGravity(true); break; case 64: @@ -746,6 +646,13 @@ public: # npc_qiraj_war_spawn ######*/ +enum QirajWarSpawn +{ + SPELL_STONED_CHANNEL_CAST_VISUAL = 15533, + SPELL_SUMMON_POISON_CLOUD = 24319, + SPELL_STONED = 33652 +}; + class npc_qiraj_war_spawn : public CreatureScript { public: @@ -793,22 +700,22 @@ public: { if (!Timers) { - if (me->GetEntry() == 15424 || me->GetEntry() == 15422 || me->GetEntry() == 15414) //all but Kaldorei Soldiers + if (me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) //all but Kaldorei Soldiers { SpellTimer1 = SpawnCast[1].Timer1; SpellTimer2 = SpawnCast[2].Timer1; SpellTimer3 = SpawnCast[3].Timer1; } - if (me->GetEntry() == 15423 || me->GetEntry() == 15424 || me->GetEntry() == 15422 || me->GetEntry() == 15414) + if (me->GetEntry() == NPC_KALDOREI_INFANTRY || me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) SpellTimer4 = SpawnCast[0].Timer1; Timers = true; } - if (me->GetEntry() == 15424 || me->GetEntry() == 15422|| me->GetEntry() == 15414) + if (me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) { if (SpellTimer1 <= diff) { DoCast(me, SpawnCast[1].SpellId); - DoCast(me, 24319); + DoCast(me, SPELL_SUMMON_POISON_CLOUD); SpellTimer1 = SpawnCast[1].Timer2; } else SpellTimer1 -= diff; if (SpellTimer2 <= diff) @@ -822,38 +729,38 @@ public: SpellTimer3 = SpawnCast[3].Timer2; } else SpellTimer3 -= diff; } - if (me->GetEntry() == 15423 || me->GetEntry() == 15424 || me->GetEntry() == 15422 || me->GetEntry() == 15414) + if (me->GetEntry() == NPC_KALDOREI_INFANTRY || me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) { if (SpellTimer4 <= diff) { me->RemoveAllAttackers(); me->AttackStop(); - DoCast(me, 15533); + DoCast(me, SPELL_STONED_CHANNEL_CAST_VISUAL); SpellTimer4 = SpawnCast[0].Timer2; } else SpellTimer4 -= diff; } if (!hasTarget) { Unit* target = NULL; - if (me->GetEntry() == 15424 || me->GetEntry() == 15422 || me->GetEntry() == 15414) - target = me->FindNearestCreature(15423, 20, true); - if (me->GetEntry() == 15423) + if (me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) + target = me->FindNearestCreature(NPC_KALDOREI_INFANTRY, 20, true); + if (me->GetEntry() == NPC_KALDOREI_INFANTRY) { uint8 tar = urand(0, 2); if (tar == 0) - target = me->FindNearestCreature(15422, 20, true); + target = me->FindNearestCreature(NPC_QIRAJI_TANK, 20, true); else if (tar == 1) - target = me->FindNearestCreature(15424, 20, true); + target = me->FindNearestCreature(NPC_ANUBISATH_CONQUEROR, 20, true); else if (tar == 2) - target = me->FindNearestCreature(15414, 20, true); + target = me->FindNearestCreature(NPC_QIRAJI_WASP, 20, true); } hasTarget = true; if (target) AttackStart(target); } - if (!(me->FindNearestCreature(15379, 60))) - DoCast(me, 33652); + if (!(me->FindNearestCreature(NPC_CAELESTRASZ, 60))) + DoCast(me, SPELL_STONED); if (!UpdateVictim()) { @@ -932,7 +839,7 @@ public: if (Creature* spawn = me->SummonCreature(WavesInfo[WaveCount].CreatureId, SpawnLocation[i], TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, desptimer)) { - if (spawn->GetEntry() == 15423) + if (spawn->GetEntry() == NPC_KALDOREI_INFANTRY) spawn->SetUInt32Value(UNIT_FIELD_DISPLAYID, 15427 + rand32() % 4); if (i >= 30) WaveCount = 1; if (i >= 33) WaveCount = 2; @@ -1040,6 +947,14 @@ void npc_qiraj_war_spawn::npc_qiraj_war_spawnAI::JustDied(Unit* /*slayer*/) # go_crystalline_tear ######*/ +enum CrystallineTear +{ + ARYGOS_GNOME_FORM = 15418, + CAELESTRASZ_NIGHT_ELF_FORM = 15419, + MERITHRA_NIGHT_ELF_FORM = 15420, + ANACHRONOS_QUEST_TRIGGER_INVISIBLE = 15454 +}; + class go_crystalline_tear : public GameObjectScript { public: @@ -1049,35 +964,35 @@ public: { if (quest->GetQuestId() == QUEST_A_PAWN_ON_THE_ETERNAL_BOARD) { - if (Creature* trigger = go->FindNearestCreature(15454, 100)) + if (Creature* trigger = go->FindNearestCreature(ANACHRONOS_QUEST_TRIGGER_INVISIBLE, 100)) { - Unit* Merithra = trigger->SummonCreature(15378, -8034.535f, 1535.14f, 2.61f, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); - Unit* Caelestrasz = trigger->SummonCreature(15379, -8032.767f, 1533.148f, 2.61f, 1.5f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); - Unit* Arygos = trigger->SummonCreature(15380, -8034.52f, 1537.843f, 2.61f, 5.7f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); - /* Unit* Fandral = */ trigger->SummonCreature(15382, -8028.462f, 1535.843f, 2.61f, 3.141592f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); - Creature* Anachronos = trigger->SummonCreature(15381, -8028.75f, 1538.795f, 2.61f, 4, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); + Unit* Merithra = trigger->SummonCreature(NPC_MERITHRA_OF_THE_DREAM, -8034.535f, 1535.14f, 2.61f, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); + Unit* Caelestrasz = trigger->SummonCreature(NPC_CAELESTRASZ, -8032.767f, 1533.148f, 2.61f, 1.5f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); + Unit* Arygos = trigger->SummonCreature(NPC_ARYGOS, -8034.52f, 1537.843f, 2.61f, 5.7f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); + /* Unit* Fandral = */ trigger->SummonCreature(NPC_FANDRAL_STAGHELM, -8028.462f, 1535.843f, 2.61f, 3.141592f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); + Creature* Anachronos = trigger->SummonCreature(NPC_ANACHRONOS, -8028.75f, 1538.795f, 2.61f, 4, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 220000); if (Merithra) { - Merithra->SetUInt32Value(UNIT_NPC_FLAGS, 0); + Merithra->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); Merithra->SetUInt32Value(UNIT_FIELD_BYTES_1, 0); - Merithra->SetUInt32Value(UNIT_FIELD_DISPLAYID, 15420); + Merithra->SetUInt32Value(UNIT_FIELD_DISPLAYID, MERITHRA_NIGHT_ELF_FORM); Merithra->setFaction(35); } if (Caelestrasz) { - Caelestrasz->SetUInt32Value(UNIT_NPC_FLAGS, 0); + Caelestrasz->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); Caelestrasz->SetUInt32Value(UNIT_FIELD_BYTES_1, 0); - Caelestrasz->SetUInt32Value(UNIT_FIELD_DISPLAYID, 15419); + Caelestrasz->SetUInt32Value(UNIT_FIELD_DISPLAYID, CAELESTRASZ_NIGHT_ELF_FORM); Caelestrasz->setFaction(35); } if (Arygos) { - Arygos->SetUInt32Value(UNIT_NPC_FLAGS, 0); + Arygos->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); Arygos->SetUInt32Value(UNIT_FIELD_BYTES_1, 0); - Arygos->SetUInt32Value(UNIT_FIELD_DISPLAYID, 15418); + Arygos->SetUInt32Value(UNIT_FIELD_DISPLAYID, ARYGOS_GNOME_FORM); Arygos->setFaction(35); } @@ -1107,112 +1022,107 @@ public: enum WSSpells { - SPELL_PUNISHMENT = 24803, - SPELL_SPAWN_IN = 25035, - - AURA_TWILIGHT_SET = 24746, - AURA_MEDALLION = 24748, - AURA_RING = 24782, - - SPELL_TEMPLAR_RANDOM = 24745, - SPELL_TEMPLAR_FIRE = 24747, - SPELL_TEMPLAR_AIR = 24757, - SPELL_TEMPLAR_EARTH = 24759, - SPELL_TEMPLAR_WATER = 24761, - - SPELL_DUKE_RANDOM = 24762, - SPELL_DUKE_FIRE = 24766, - SPELL_DUKE_AIR = 24769, - SPELL_DUKE_EARTH = 24771, - SPELL_DUKE_WATER = 24773, - - SPELL_ROYAL_RANDOM = 24785, - SPELL_ROYAL_FIRE = 24787, - SPELL_ROYAL_AIR = 24791, - SPELL_ROYAL_EARTH = 24792, - SPELL_ROYAL_WATER = 24793 + AURA_TWILIGHT_SET = 24746, + AURA_MEDALLION = 24748, + AURA_RING = 24782, + + SPELL_TEMPLAR_RANDOM = 24745, + SPELL_TEMPLAR_FIRE = 24747, + SPELL_TEMPLAR_AIR = 24757, + SPELL_TEMPLAR_EARTH = 24759, + SPELL_TEMPLAR_WATER = 24761, + + SPELL_DUKE_RANDOM = 24762, + SPELL_DUKE_FIRE = 24766, + SPELL_DUKE_AIR = 24769, + SPELL_DUKE_EARTH = 24771, + SPELL_DUKE_WATER = 24773, + + SPELL_ROYAL_RANDOM = 24785, + SPELL_ROYAL_FIRE = 24787, + SPELL_ROYAL_AIR = 24791, + SPELL_ROYAL_EARTH = 24792, + SPELL_ROYAL_WATER = 24793, + + SPELL_PUNISHMENT = 24803, + SPELL_SPAWN_IN = 25035 }; enum WSGossip { - GOSSIPID_LESSER_WS = 6540, - GOSSIPID_WS = 6542, - GOSSIPID_GREATER_WS = 6543 + OPTION_ID_WS_RANDOM = 0, + OPTION_ID_1_CRIMSON = 1, + OPTION_ID_2_AZURE = 2, + OPTION_ID_3_EARTHEN = 3, + OPTION_ID_4_HOARY = 4, + OPTION_ID_1_CYNDERS = 1, + OPTION_ID_2_FATHOMS = 2, + OPTION_ID_3_SHARDS = 3, + OPTION_ID_4_ZEPHYRS = 4, + OPTION_ID_1_SKALDRENOX = 1, + OPTION_ID_2_SKWOL = 2, + OPTION_ID_3_KAZUM = 3, + OPTION_ID_4_WHIRLAXIS = 4, + GOSSIP_ID_LESSER_WS = 6540, + GOSSIP_ID_WIND_STONE = 6542, + GOSSIP_ID_GREATER_WS = 6543 }; enum WSCreatures { - NPC_TEMPLAR_FIRE = 15209, - NPC_TEMPLAR_WATER = 15211, - NPC_TEMPLAR_AIR = 15212, - NPC_TEMPLAR_EARTH = 15307, - - NPC_DUKE_FIRE = 15206, - NPC_DUKE_WATER = 15207, - NPC_DUKE_EARTH = 15208, - NPC_DUKE_AIR = 15220, - - NPC_ROYAL_FIRE = 15203, - NPC_ROYAL_AIR = 15204, - NPC_ROYAL_EARTH = 15205, - NPC_ROYAL_WATER = 15305 + NPC_TEMPLAR_FIRE = 15209, + NPC_TEMPLAR_WATER = 15211, + NPC_TEMPLAR_AIR = 15212, + NPC_TEMPLAR_EARTH = 15307, + + NPC_DUKE_FIRE = 15206, + NPC_DUKE_WATER = 15207, + NPC_DUKE_EARTH = 15208, + NPC_DUKE_AIR = 15220, + + NPC_ROYAL_FIRE = 15203, + NPC_ROYAL_AIR = 15204, + NPC_ROYAL_EARTH = 15205, + NPC_ROYAL_WATER = 15305 }; enum WSItems { - ITEM_TEMPLAR_FIRE = 20416, - ITEM_TEMPLAR_EARTH = 20419, - ITEM_TEMPLAR_WATER = 20420, - ITEM_TEMPLAR_AIR = 20418, - - ITEM_DUKE_FIRE = 20432, - ITEM_DUKE_EARTH = 20435, - ITEM_DUKE_WATER = 20436, - ITEM_DUKE_AIR = 20433, - - ITEM_ROYAL_FIRE = 20447, - ITEM_ROYAL_EARTH = 20449, - ITEM_ROYAL_WATER = 20450, - ITEM_ROYAL_AIR = 20448, + ITEM_TEMPLAR_FIRE = 20416, + ITEM_TEMPLAR_AIR = 20418, + ITEM_TEMPLAR_EARTH = 20419, + ITEM_TEMPLAR_WATER = 20420, + + ITEM_DUKE_FIRE = 20432, + ITEM_DUKE_AIR = 20433, + ITEM_DUKE_EARTH = 20435, + ITEM_DUKE_WATER = 20436, + + ITEM_ROYAL_FIRE = 20447, + ITEM_ROYAL_AIR = 20448, + ITEM_ROYAL_EARTH = 20449, + ITEM_ROYAL_WATER = 20450 }; enum WS { - TEMPLAR = 0, - DUKE = 1, - ROYAL = 2, - - FIRE = 0x1, - WATER = 0x2, - EARTH = 0x4, - AIR = 0x8 -}; + TEMPLAR = 0, + DUKE = 1, + ROYAL = 2, + + FIRE = 0x1, + WATER = 0x2, + EARTH = 0x4, + AIR = 0x8 +}; enum WSTexts { - SAY_TEMPLAR_AGGRO = 0, - SAY_DUKE_AGGRO = 0, - YELL_ROYAL_AGGRO = 0 + SAY_TEMPLAR_AGGRO = 0, + SAY_DUKE_AGGRO = 0, + YELL_ROYAL_AGGRO = 0 }; -#define GOSSIP_TEMPLAR_RANDOM "I am no cultist, you monster! Come to me and face your destruction!" -#define GOSSIP_TEMPLAR_FIRE "Crimson Templar! I hold your signet! Heed my call!" -#define GOSSIP_TEMPLAR_EARTH "Earthen Templar! I hold your signet! Heed my call!" -#define GOSSIP_TEMPLAR_AIR "Hoary Templar! I hold your signet! Heed my call!" -#define GOSSIP_TEMPLAR_WATER "Azure Templar! I hold your signet! Heed my call!" - -#define GOSSIP_DUKE_RANDOM "You will listen to this, vile duke! I am not your Twilight's Hammer lapdog! I am here to challenge you! Come! Come, and meet your death..." -#define GOSSIP_DUKE_FIRE "Duke of Cynders! I hold your signet! Heed my call!" -#define GOSSIP_DUKE_EARTH "The Duke of Shards! I hold your signet! Heed my call!" -#define GOSSIP_DUKE_AIR "The Duke of Zephyrs! I hold your signet! Heed my call!" -#define GOSSIP_DUKE_WATER "The Duke of Fathoms! I hold your signet! Heed my call!" - -#define GOSSIP_ROYAL_RANDOM "The day of the judgement has come, fiend! I challenge you to battle!" -#define GOSSIP_ROYAL_FIRE "Prince Skaldrenox! I hold your signet! Heed my call!" -#define GOSSIP_ROYAL_EARTH "Baron Kazum! I hold your signet! Heed my call!" -#define GOSSIP_ROYAL_AIR "High Marshal Whirlaxis! I hold your signet! Heed my call!" -#define GOSSIP_ROYAL_WATER "Lord Skwol! I hold your signet! Heed my call!" - class go_wind_stone : public GameObjectScript { public: @@ -1294,7 +1204,7 @@ class go_wind_stone : public GameObjectScript case NPC_TEMPLAR_WATER: case NPC_TEMPLAR_AIR: case NPC_TEMPLAR_EARTH: - summons->AI()->Talk(SAY_TEMPLAR_AGGRO); + summons->AI()->Talk(SAY_TEMPLAR_AGGRO, player); break; case NPC_DUKE_FIRE: @@ -1323,10 +1233,10 @@ class go_wind_stone : public GameObjectScript uint32 gossipId = go->GetGOInfo()->GetGossipMenuId(); switch (gossipId) { - case GOSSIPID_LESSER_WS: + case GOSSIP_ID_LESSER_WS: { if (rank >= 1) // 1 or 2 or 3 - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEMPLAR_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_LESSER_WS, OPTION_ID_WS_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); else { go->CastSpell(player, SPELL_PUNISHMENT); @@ -1335,19 +1245,19 @@ class go_wind_stone : public GameObjectScript uint8 item = GetItems(player, TEMPLAR); if (item & FIRE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEMPLAR_FIRE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_LESSER_WS, OPTION_ID_1_CRIMSON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); if (item & WATER) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEMPLAR_WATER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_LESSER_WS, OPTION_ID_2_AZURE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); if (item & EARTH) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEMPLAR_EARTH, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_LESSER_WS, OPTION_ID_3_EARTHEN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); if (item & AIR) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_TEMPLAR_AIR, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_LESSER_WS, OPTION_ID_4_HOARY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); break; } - case GOSSIPID_WS: + case GOSSIP_ID_WIND_STONE: { if (rank >= 2) // 2 or 3 - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DUKE_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_WIND_STONE, OPTION_ID_WS_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); else { go->CastSpell(player, SPELL_PUNISHMENT); @@ -1356,19 +1266,19 @@ class go_wind_stone : public GameObjectScript uint8 item = GetItems(player, DUKE); if (item & FIRE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DUKE_FIRE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_WIND_STONE, OPTION_ID_1_CYNDERS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); if (item & WATER) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DUKE_WATER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_WIND_STONE, OPTION_ID_2_FATHOMS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8); if (item & EARTH) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DUKE_EARTH, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_WIND_STONE, OPTION_ID_3_SHARDS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9); if (item & AIR) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_DUKE_AIR, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 10); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_WIND_STONE, OPTION_ID_4_ZEPHYRS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 10); break; } - case GOSSIPID_GREATER_WS: + case GOSSIP_ID_GREATER_WS: { if (rank == 3) // 3 - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ROYAL_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_GREATER_WS, OPTION_ID_WS_RANDOM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 11); else { go->CastSpell(player, SPELL_PUNISHMENT); @@ -1377,13 +1287,13 @@ class go_wind_stone : public GameObjectScript uint8 item = GetItems(player, ROYAL); if (item & FIRE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ROYAL_FIRE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 12); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_GREATER_WS, OPTION_ID_1_SKALDRENOX, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 12); if (item & WATER) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ROYAL_WATER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 13); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_GREATER_WS, OPTION_ID_2_SKWOL, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 13); if (item & EARTH) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ROYAL_EARTH, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 14); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_GREATER_WS, OPTION_ID_3_KAZUM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 14); if (item & AIR) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ROYAL_AIR, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 15); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_ID_GREATER_WS, OPTION_ID_4_WHIRLAXIS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 15); break; } default: @@ -1462,6 +1372,5 @@ void AddSC_silithus() new npc_anachronos_quest_trigger(); new npc_anachronos_the_ancient(); new npc_qiraj_war_spawn(); - new npcs_rutgar_and_frankal(); new go_wind_stone(); } diff --git a/src/server/scripts/Kalimdor/zone_tanaris.cpp b/src/server/scripts/Kalimdor/zone_tanaris.cpp index 22b4c86cbcd..966bbaec1da 100644 --- a/src/server/scripts/Kalimdor/zone_tanaris.cpp +++ b/src/server/scripts/Kalimdor/zone_tanaris.cpp @@ -19,15 +19,13 @@ /* ScriptData SDName: Tanaris SD%Complete: 80 -SDComment: Quest support: 648, 1560, 2954, 4005, 10277, 10279(Special flight path). +SDComment: Quest support: 648, 1560, 4005, 10277 SDCategory: Tanaris EndScriptData */ /* ContentData npc_aquementas npc_custodian_of_time -npc_steward_of_time -npc_stone_watcher_of_norgannon npc_OOX17 npc_tooga EndContentData */ @@ -298,116 +296,6 @@ public: }; /*###### -## npc_steward_of_time -######*/ - -#define GOSSIP_ITEM_FLIGHT "Please take me to the master's lair." - -class npc_steward_of_time : public CreatureScript -{ -public: - npc_steward_of_time() : CreatureScript("npc_steward_of_time") { } - - bool OnQuestAccept(Player* player, Creature* /*creature*/, Quest const* quest) override - { - if (quest->GetQuestId() == 10279) //Quest: To The Master's Lair - player->CastSpell(player, 34891, true); //(Flight through Caverns) - - return false; - } - - bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF + 1) - player->CastSpell(player, 34891, true); //(Flight through Caverns) - - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(10279) == QUEST_STATUS_INCOMPLETE || player->GetQuestRewardStatus(10279)) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_FLIGHT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->SEND_GOSSIP_MENU(9978, creature->GetGUID()); - } - else - player->SEND_GOSSIP_MENU(9977, creature->GetGUID()); - - return true; - } - -}; - -/*###### -## npc_stone_watcher_of_norgannon -######*/ - -#define GOSSIP_ITEM_NORGANNON_1 "What function do you serve?" -#define GOSSIP_ITEM_NORGANNON_2 "What are the Plates of Uldum?" -#define GOSSIP_ITEM_NORGANNON_3 "Where are the Plates of Uldum?" -#define GOSSIP_ITEM_NORGANNON_4 "Excuse me? We've been \"reschedueled for visitations\"? What does that mean?!" -#define GOSSIP_ITEM_NORGANNON_5 "So, what's inside Uldum?" -#define GOSSIP_ITEM_NORGANNON_6 "I will return when i have the Plates of Uldum." - -class npc_stone_watcher_of_norgannon : public CreatureScript -{ -public: - npc_stone_watcher_of_norgannon() : CreatureScript("npc_stone_watcher_of_norgannon") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(1675, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - player->SEND_GOSSIP_MENU(1676, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - player->SEND_GOSSIP_MENU(1677, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); - player->SEND_GOSSIP_MENU(1678, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_6, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+5); - player->SEND_GOSSIP_MENU(1679, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+5: - player->CLOSE_GOSSIP_MENU(); - player->AreaExploredOrEventHappens(2954); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(2954) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_NORGANNON_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - - player->SEND_GOSSIP_MENU(1674, creature->GetGUID()); - - return true; - } - -}; - -/*###### ## npc_OOX17 ######*/ @@ -672,8 +560,6 @@ void AddSC_tanaris() { new npc_aquementas(); new npc_custodian_of_time(); - new npc_steward_of_time(); - new npc_stone_watcher_of_norgannon(); new npc_OOX17(); new npc_tooga(); } diff --git a/src/server/scripts/Kalimdor/zone_the_barrens.cpp b/src/server/scripts/Kalimdor/zone_the_barrens.cpp index 852cd62c277..7a963d066b6 100644 --- a/src/server/scripts/Kalimdor/zone_the_barrens.cpp +++ b/src/server/scripts/Kalimdor/zone_the_barrens.cpp @@ -43,38 +43,37 @@ EndContentData */ ## npc_beaten_corpse ######*/ -#define GOSSIP_CORPSE "Examine corpse in detail..." - enum BeatenCorpse { - QUEST_LOST_IN_BATTLE = 4921 + GOSSIP_OPTION_ID_BEATEN_CORPSE = 0, + GOSSIP_MENU_OPTION_INSPECT_BODY = 2871 }; class npc_beaten_corpse : public CreatureScript { -public: - npc_beaten_corpse() : CreatureScript("npc_beaten_corpse") { } + public: + npc_beaten_corpse() : CreatureScript("npc_beaten_corpse") { } - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF +1) + struct npc_beaten_corpseAI : public ScriptedAI { - player->SEND_GOSSIP_MENU(3558, creature->GetGUID()); - player->TalkedToCreature(creature->GetEntry(), creature->GetGUID()); - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (player->GetQuestStatus(QUEST_LOST_IN_BATTLE) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(QUEST_LOST_IN_BATTLE) == QUEST_STATUS_COMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_CORPSE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + npc_beaten_corpseAI(Creature* creature) : ScriptedAI(creature) + { + } - player->SEND_GOSSIP_MENU(3557, creature->GetGUID()); - return true; - } + void sGossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override + { + if (menuId == GOSSIP_MENU_OPTION_INSPECT_BODY && gossipListId == GOSSIP_OPTION_ID_BEATEN_CORPSE) + { + player->CLOSE_GOSSIP_MENU(); + player->TalkedToCreature(me->GetEntry(), me->GetGUID()); + } + } + }; + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_beaten_corpseAI(creature); + } }; /*###### @@ -552,7 +551,7 @@ public: { if (!HasEscortState(STATE_ESCORT_ESCORTING)) { - if (me->getStandState() == UNIT_STAND_STATE_DEAD) + if (me->GetStandState() == UNIT_STAND_STATE_DEAD) me->SetStandState(UNIT_STAND_STATE_STAND); IsPostEvent = false; diff --git a/src/server/scripts/Kalimdor/zone_thousand_needles.cpp b/src/server/scripts/Kalimdor/zone_thousand_needles.cpp index 85c3a621239..2a606856af6 100644 --- a/src/server/scripts/Kalimdor/zone_thousand_needles.cpp +++ b/src/server/scripts/Kalimdor/zone_thousand_needles.cpp @@ -19,7 +19,7 @@ /* ScriptData SDName: Thousand Needles SD%Complete: 100 -SDComment: Support for Quest: 1950, 4770, 4904, 4966, 5151. +SDComment: Support for Quest: 4770, 4904, 4966, 5151. SDCategory: Thousand Needles EndScriptData */ @@ -27,7 +27,6 @@ EndScriptData */ npc_kanati npc_lakota_windsong npc_swiftmountain -npc_plucky npc_enraged_panther go_panther_cage EndContentData */ @@ -44,10 +43,9 @@ EndContentData */ enum Kanati { - SAY_KAN_START = 0, - - QUEST_PROTECT_KANATI = 4966, - NPC_GALAK_ASS = 10720 + SAY_KAN_START = 0, + QUEST_PROTECT_KANATI = 4966, + NPC_GALAK_ASS = 10720 }; Position const GalakLoc = {-4867.387695f, -1357.353760f, -48.226f, 0.0f}; @@ -112,19 +110,19 @@ public: enum Lakota { - SAY_LAKO_START = 0, - SAY_LAKO_LOOK_OUT = 1, - SAY_LAKO_HERE_COME = 2, - SAY_LAKO_MORE = 3, - SAY_LAKO_END = 4, - - QUEST_FREE_AT_LAST = 4904, - NPC_GRIM_BANDIT = 10758, - FACTION_ESCORTEE_LAKO = 232, //guessed - - ID_AMBUSH_1 = 0, - ID_AMBUSH_2 = 2, - ID_AMBUSH_3 = 4 + SAY_LAKO_START = 0, + SAY_LAKO_LOOK_OUT = 1, + SAY_LAKO_HERE_COME = 2, + SAY_LAKO_MORE = 3, + SAY_LAKO_END = 4, + + QUEST_FREE_AT_LAST = 4904, + NPC_GRIM_BANDIT = 10758, + FACTION_ESCORTEE_LAKO = 232, //guessed + + ID_AMBUSH_1 = 0, + ID_AMBUSH_2 = 2, + ID_AMBUSH_3 = 4 }; Position const BanditLoc[6] = @@ -183,6 +181,7 @@ public: DoSpawnBandits(ID_AMBUSH_3); break; case 45: + Talk(SAY_LAKO_END); if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_FREE_AT_LAST, me); break; @@ -195,7 +194,6 @@ public: me->SummonCreature(NPC_GRIM_BANDIT, BanditLoc[i+AmbushId], TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); } }; - }; /*###### @@ -204,13 +202,13 @@ public: enum Packa { - SAY_START = 0, - SAY_WYVERN = 1, - SAY_COMPLETE = 2, + SAY_START = 0, + SAY_WYVERN = 1, + SAY_COMPLETE = 2, - QUEST_HOMEWARD = 4770, - NPC_WYVERN = 4107, - FACTION_ESCORTEE = 232 //guessed + QUEST_HOMEWARD = 4770, + NPC_WYVERN = 4107, + FACTION_ESCORTEE = 232 //guessed }; Position const WyvernLoc[3] = @@ -275,137 +273,10 @@ public: }; }; -/*##### -# npc_plucky -######*/ - -#define GOSSIP_P "Please tell me the Phrase.." - -enum Plucky -{ - FACTION_FRIENDLY = 35, - QUEST_SCOOP = 1950, - SPELL_PLUCKY_HUMAN = 9192, - SPELL_PLUCKY_CHICKEN = 9220 -}; - -class npc_plucky : public CreatureScript -{ -public: - npc_plucky() : CreatureScript("npc_plucky") { } - - bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->CLOSE_GOSSIP_MENU(); - player->CompleteQuest(QUEST_SCOOP); - break; - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (player->GetQuestStatus(QUEST_SCOOP) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_P, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(738, creature->GetGUID()); - - return true; - } - - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_pluckyAI(creature); - } - - struct npc_pluckyAI : public ScriptedAI - { - npc_pluckyAI(Creature* creature) : ScriptedAI(creature) - { - Initialize(); - NormFaction = creature->getFaction(); - } - - void Initialize() - { - ResetTimer = 120000; - } - - uint32 NormFaction; - uint32 ResetTimer; - - void Reset() override - { - Initialize(); - - if (me->getFaction() != NormFaction) - me->setFaction(NormFaction); - - if (me->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP)) - me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - - DoCast(me, SPELL_PLUCKY_CHICKEN, false); - } - - void ReceiveEmote(Player* player, uint32 TextEmote) override - { - if (player->GetQuestStatus(QUEST_SCOOP) == QUEST_STATUS_INCOMPLETE) - { - if (TextEmote == TEXT_EMOTE_BECKON) - { - me->setFaction(FACTION_FRIENDLY); - me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - DoCast(me, SPELL_PLUCKY_HUMAN, false); - } - } - - if (TextEmote == TEXT_EMOTE_CHICKEN) - { - if (me->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP)) - return; - else - { - me->setFaction(FACTION_FRIENDLY); - me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - DoCast(me, SPELL_PLUCKY_HUMAN, false); - me->HandleEmoteCommand(EMOTE_ONESHOT_WAVE); - } - } - } - - void UpdateAI(uint32 Diff) override - { - if (me->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP)) - { - if (ResetTimer <= Diff) - { - if (!me->GetVictim()) - EnterEvadeMode(); - else - me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - - return; - } - else - ResetTimer -= Diff; - } - - if (!UpdateVictim()) - return; - - DoMeleeAttackIfReady(); - } - }; - -}; - enum PantherCage { - ENRAGED_PANTHER = 10992 + QUEST_HYPERCAPACITOR_GIZMO = 5151, + ENRAGED_PANTHER = 10992 }; class go_panther_cage : public GameObjectScript @@ -416,7 +287,7 @@ public: bool OnGossipHello(Player* player, GameObject* go) override { go->UseDoorOrButton(); - if (player->GetQuestStatus(5151) == QUEST_STATUS_INCOMPLETE) + if (player->GetQuestStatus(QUEST_HYPERCAPACITOR_GIZMO) == QUEST_STATUS_INCOMPLETE) { if (Creature* panther = go->FindNearestCreature(ENRAGED_PANTHER, 5, true)) { @@ -466,7 +337,6 @@ void AddSC_thousand_needles() new npc_kanati(); new npc_lakota_windsong(); new npc_paoka_swiftmountain(); - new npc_plucky(); new npc_enraged_panther(); new go_panther_cage(); } diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp index ab09dd45710..2f97b5a8055 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp @@ -16,7 +16,8 @@ */ /* - * Comment: Complete - BUT THE TRIGGER NEEDS DATA WHETHER THE PRISON OF TALDARAM IS OFFLINE ! + * Comment: Visuals missing, de-germanize code, wow 3.3.5a-ize + * Patch 3.3.2 (2010-01-02): Jedoga Shadowseeker now only ascends once during the encounter. */ #include "ScriptMgr.h" @@ -454,11 +455,11 @@ public: float distance = me->GetDistance(JedogaPosition[1]); if (distance < 9.0f) - me->SetSpeed(MOVE_WALK, 0.5f, true); + me->SetSpeedRate(MOVE_WALK, 0.5f); else if (distance < 15.0f) - me->SetSpeed(MOVE_WALK, 0.75f, true); + me->SetSpeedRate(MOVE_WALK, 0.75f); else if (distance < 20.0f) - me->SetSpeed(MOVE_WALK, 1.0f, true); + me->SetSpeedRate(MOVE_WALK, 1.0f); me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MovePoint(1, JedogaPosition[1]); diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp index e25f64f61aa..04b62f77e9a 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp @@ -178,7 +178,7 @@ class boss_prince_taldaram : public CreatureScript if (Unit* embraceTarget = GetEmbraceTarget()) { me->GetMotionMaster()->Clear(); - me->SetSpeed(MOVE_WALK, 2.0f, true); + me->SetSpeedRate(MOVE_WALK, 2.0f); me->GetMotionMaster()->MoveChase(embraceTarget); } events.ScheduleEvent(EVENT_VANISHED, 1300); @@ -188,7 +188,7 @@ class boss_prince_taldaram : public CreatureScript DoCast(embraceTarget, SPELL_EMBRACE_OF_THE_VAMPYR); Talk(SAY_FEED); me->GetMotionMaster()->Clear(); - me->SetSpeed(MOVE_WALK, 1.0f, true); + me->SetSpeedRate(MOVE_WALK, 1.0f); me->GetMotionMaster()->MoveChase(me->GetVictim()); events.ScheduleEvent(EVENT_FEEDING, 20000); break; diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp index 16cfb30e2dc..2df0fceab9c 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp @@ -156,7 +156,7 @@ public: ImpaleTarget = impaleTarget->GetGUID(); impaleTarget->SetReactState(REACT_PASSIVE); impaleTarget->SetDisplayId(DISPLAY_INVISIBLE); - impaleTarget->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE|UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE); + impaleTarget->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL|UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE); return impaleTarget; } diff --git a/src/server/scripts/Northrend/CMakeLists.txt b/src/server/scripts/Northrend/CMakeLists.txt deleted file mode 100644 index 1dc453ad416..00000000000 --- a/src/server/scripts/Northrend/CMakeLists.txt +++ /dev/null @@ -1,199 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - Northrend/zone_wintergrasp.cpp - Northrend/isle_of_conquest.cpp - Northrend/zone_storm_peaks.cpp - Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp - Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp - Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h - Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp - Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp - Northrend/Ulduar/HallsOfLightning/boss_loken.cpp - Northrend/Ulduar/Ulduar/boss_general_vezax.cpp - Northrend/Ulduar/Ulduar/boss_thorim.cpp - Northrend/Ulduar/Ulduar/boss_ignis.cpp - Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp - Northrend/Ulduar/Ulduar/instance_ulduar.cpp - Northrend/Ulduar/Ulduar/boss_auriaya.cpp - Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp - Northrend/Ulduar/Ulduar/boss_hodir.cpp - Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp - Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp - Northrend/Ulduar/Ulduar/boss_xt002.cpp - Northrend/Ulduar/Ulduar/boss_mimiron.cpp - Northrend/Ulduar/Ulduar/ulduar.h - Northrend/Ulduar/Ulduar/boss_freya.cpp - Northrend/Ulduar/Ulduar/boss_razorscale.cpp - Northrend/Ulduar/Ulduar/boss_kologarn.cpp - Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp - Northrend/Ulduar/HallsOfStone/halls_of_stone.h - Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp - Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp - Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp - Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp - Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp - Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h - Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp - Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp - Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp - Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h - Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp - Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp - Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp - Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp - Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp - Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h - Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp - Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp - Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp - Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp - Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp - Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp - Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp - Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp - Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h - Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp - Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp - Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp - Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp - Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp - Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h - Northrend/Nexus/EyeOfEternity/boss_malygos.cpp - Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp - Northrend/Nexus/EyeOfEternity/eye_of_eternity.h - Northrend/Nexus/Oculus/boss_eregos.cpp - Northrend/Nexus/Oculus/boss_drakos.cpp - Northrend/Nexus/Oculus/oculus.h - Northrend/Nexus/Oculus/boss_varos.cpp - Northrend/Nexus/Oculus/boss_urom.cpp - Northrend/Nexus/Oculus/oculus.cpp - Northrend/Nexus/Oculus/instance_oculus.cpp - Northrend/Nexus/Nexus/boss_nexus_commanders.cpp - Northrend/Nexus/Nexus/boss_ormorok.cpp - Northrend/Nexus/Nexus/boss_magus_telestra.cpp - Northrend/Nexus/Nexus/instance_nexus.cpp - Northrend/Nexus/Nexus/boss_keristrasza.cpp - Northrend/Nexus/Nexus/boss_anomalus.cpp - Northrend/Nexus/Nexus/nexus.h - Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h - Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp - Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp - Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h - Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp - Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp - Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp - Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp - Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp - Northrend/Naxxramas/boss_loatheb.cpp - Northrend/Naxxramas/boss_anubrekhan.cpp - Northrend/Naxxramas/boss_maexxna.cpp - Northrend/Naxxramas/boss_patchwerk.cpp - Northrend/Naxxramas/boss_gothik.cpp - Northrend/Naxxramas/boss_faerlina.cpp - Northrend/Naxxramas/boss_gluth.cpp - Northrend/Naxxramas/boss_four_horsemen.cpp - Northrend/Naxxramas/naxxramas.h - Northrend/Naxxramas/boss_kelthuzad.cpp - Northrend/Naxxramas/boss_heigan.cpp - Northrend/Naxxramas/boss_thaddius.cpp - Northrend/Naxxramas/boss_razuvious.cpp - Northrend/Naxxramas/boss_sapphiron.cpp - Northrend/Naxxramas/instance_naxxramas.cpp - Northrend/Naxxramas/boss_grobbulus.cpp - Northrend/Naxxramas/boss_noth.cpp - Northrend/zone_crystalsong_forest.cpp - Northrend/VaultOfArchavon/boss_archavon.cpp - Northrend/VaultOfArchavon/boss_koralon.cpp - Northrend/VaultOfArchavon/vault_of_archavon.h - Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp - Northrend/VaultOfArchavon/boss_emalon.cpp - Northrend/VaultOfArchavon/boss_toravon.cpp - Northrend/zone_sholazar_basin.cpp - Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp - Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp - Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp - Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp - Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp - Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h - Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp - Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp - Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h - Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp - Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp - Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp - Northrend/zone_dragonblight.cpp - Northrend/zone_grizzly_hills.cpp - Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h - Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp - Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp - Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp - Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp - Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp - Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp - Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp - Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp - Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp - Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp - Northrend/AzjolNerub/Ahnkahet/ahnkahet.h - Northrend/VioletHold/boss_zuramat.cpp - Northrend/VioletHold/instance_violet_hold.cpp - Northrend/VioletHold/boss_lavanthor.cpp - Northrend/VioletHold/boss_cyanigosa.cpp - Northrend/VioletHold/violet_hold.h - Northrend/VioletHold/boss_ichoron.cpp - Northrend/VioletHold/boss_moragg.cpp - Northrend/VioletHold/boss_xevozz.cpp - Northrend/VioletHold/boss_erekem.cpp - Northrend/VioletHold/violet_hold.cpp - Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp - Northrend/IcecrownCitadel/icecrown_citadel.cpp - Northrend/IcecrownCitadel/icecrown_citadel.h - Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp - Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp - Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp - Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp - Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp - Northrend/IcecrownCitadel/boss_festergut.cpp - Northrend/IcecrownCitadel/boss_rotface.cpp - Northrend/IcecrownCitadel/boss_professor_putricide.cpp - Northrend/IcecrownCitadel/boss_blood_prince_council.cpp - Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp - Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp - Northrend/IcecrownCitadel/boss_sindragosa.cpp - Northrend/IcecrownCitadel/boss_the_lich_king.cpp - Northrend/zone_zuldrak.cpp - Northrend/zone_icecrown.cpp - Northrend/Gundrak/boss_slad_ran.cpp - Northrend/Gundrak/instance_gundrak.cpp - Northrend/Gundrak/boss_drakkari_colossus.cpp - Northrend/Gundrak/gundrak.h - Northrend/Gundrak/boss_gal_darah.cpp - Northrend/Gundrak/boss_moorabi.cpp - Northrend/Gundrak/boss_eck.cpp - Northrend/zone_borean_tundra.cpp - Northrend/zone_howling_fjord.cpp - Northrend/zone_dalaran.cpp - Northrend/DraktharonKeep/boss_trollgore.cpp - Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp - Northrend/DraktharonKeep/boss_novos.cpp - Northrend/DraktharonKeep/drak_tharon_keep.h - Northrend/DraktharonKeep/boss_tharon_ja.cpp - Northrend/DraktharonKeep/boss_king_dred.cpp -) - -message(" -> Prepared: Northrend") diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp index 7b8ca41772f..d6682e272fd 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp @@ -137,7 +137,8 @@ enum Events EVENT_CHECK_CORPOREALITY = 13, EVENT_SHADOW_PULSARS_SHOOT = 14, EVENT_TRIGGER_BERSERK = 15, - EVENT_TWILIGHT_MENDING = 16 + EVENT_TWILIGHT_MENDING = 16, + EVENT_ACTIVATE_EMBERS = 17 }; enum Actions @@ -150,7 +151,9 @@ enum Actions ACTION_MONITOR_CORPOREALITY = 3, // Orb Carrier - ACTION_SHOOT = 4 + ACTION_WARNING_SHOOT = 4, + ACTION_SHOOT = 5, + ACTION_ACTIVATE_EMBERS = 6 }; enum Phases @@ -168,8 +171,7 @@ enum Misc DATA_MATERIAL_DAMAGE_TAKEN = 2, DATA_STACKS_DISPELLED = 3, DATA_FIGHT_PHASE = 4, - DATA_EVADE_METHOD = 5, - DATA_SPAWNED_FLAMES = 6, + DATA_SPAWNED_FLAMES = 5, }; enum OrbCarrierSeats @@ -189,6 +191,7 @@ enum CorporealityEvent }; Position const HalionSpawnPos = {3156.67f, 533.8108f, 72.98822f, 3.159046f}; +Position const HalionRespawnPos = {3156.625f, 533.2674f, 72.97205f, 0.0f}; uint8 const MAX_CORPOREALITY_STATE = 11; @@ -212,132 +215,39 @@ CorporealityEntry const _corporealityReference[MAX_CORPOREALITY_STATE] = { {74831, 74836} }; -struct generic_halionAI : public BossAI -{ - generic_halionAI(Creature* creature, uint32 bossId) : BossAI(creature, bossId), _canEvade(false) { } - - void EnterCombat(Unit* /*who*/) override - { - _EnterCombat(); - me->AddAura(SPELL_TWILIGHT_PRECISION, me); - _canEvade = false; - events.ScheduleEvent(EVENT_CLEAVE, urand(8000, 10000)); - events.ScheduleEvent(EVENT_TAIL_LASH, 10000); - events.ScheduleEvent(EVENT_BREATH, urand(10000, 15000)); - } - - void Reset() override - { - _canEvade = false; - _Reset(); - } - - void JustReachedHome() override - { - instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); - _JustReachedHome(); - } - - void ExecuteEvent(uint32 eventId) override - { - switch (eventId) - { - case EVENT_CLEAVE: - DoCastVictim(SPELL_CLEAVE); - events.ScheduleEvent(EVENT_CLEAVE, urand(8000, 10000)); - break; - case EVENT_TAIL_LASH: - DoCastAOE(SPELL_TAIL_LASH); - events.ScheduleEvent(EVENT_TAIL_LASH, 10000); - break; - case EVENT_BREATH: - DoCast(me, me->GetEntry() == NPC_HALION ? SPELL_FLAME_BREATH : SPELL_DARK_BREATH); - events.ScheduleEvent(EVENT_BREATH, urand(10000, 12000)); - break; - } - } - - void UpdateAI(uint32 diff) override - { - if (!UpdateVictim() || me->HasUnitState(UNIT_STATE_CASTING)) - return; - - events.Update(diff); - - while (uint32 eventId = events.ExecuteEvent()) - ExecuteEvent(eventId); - - DoMeleeAttackIfReady(); - } - - void SetData(uint32 index, uint32 dataValue) override - { - switch (index) - { - case DATA_EVADE_METHOD: - _canEvade = (dataValue == 1); - break; - default: - break; - } - } - - void SpellHit(Unit* /*who*/, SpellInfo const* spellInfo) override - { - if (spellInfo->Id == SPELL_TWILIGHT_MENDING) - Talk(SAY_REGENERATE); - } - -protected: - bool _canEvade; -}; - class boss_halion : public CreatureScript { public: boss_halion() : CreatureScript("boss_halion") { } - struct boss_halionAI : public generic_halionAI + struct boss_halionAI : public BossAI { - boss_halionAI(Creature* creature) : generic_halionAI(creature, DATA_HALION) - { - me->SetHomePosition(HalionSpawnPos); - } - - void Reset() override - { - generic_halionAI::Reset(); - me->SetReactState(REACT_DEFENSIVE); - me->RemoveAurasDueToSpell(SPELL_TWILIGHT_PHASING); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - } + boss_halionAI(Creature* creature) : BossAI(creature, DATA_HALION) { } void EnterEvadeMode(EvadeReason why) override { - if (why == EVADE_REASON_BOUNDARY) + if (why == EVADE_REASON_BOUNDARY || events.IsInPhase(PHASE_ONE)) if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HALION_CONTROLLER))) - controller->AI()->EnterEvadeMode(); - - // Phase 1: We always can evade. Phase 2 & 3: We can evade if and only if the controller tells us to. - if (events.IsInPhase(PHASE_ONE) || _canEvade) - generic_halionAI::EnterEvadeMode(why); + controller->AI()->EnterEvadeMode(why); } - void EnterCombat(Unit* who) override + void EnterCombat(Unit* /*who*/) override { Talk(SAY_AGGRO); events.Reset(); events.SetPhase(PHASE_ONE); - generic_halionAI::EnterCombat(who); + _EnterCombat(); + me->AddAura(SPELL_TWILIGHT_PRECISION, me); + events.ScheduleEvent(EVENT_ACTIVATE_FIREWALL, Seconds(5)); + events.ScheduleEvent(EVENT_BREATH, randtime(Seconds(5), Seconds(15))); + events.ScheduleEvent(EVENT_CLEAVE, randtime(Seconds(6), Seconds(10))); + events.ScheduleEvent(EVENT_TAIL_LASH, randtime(Seconds(7), Seconds(12))); + events.ScheduleEvent(EVENT_FIERY_COMBUSTION, randtime(Seconds(15), Seconds(18))); + events.ScheduleEvent(EVENT_METEOR_STRIKE, Seconds(18)); instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me, 1); - instance->SetBossState(DATA_HALION, IN_PROGRESS); - - events.ScheduleEvent(EVENT_ACTIVATE_FIREWALL, 5000); - events.ScheduleEvent(EVENT_METEOR_STRIKE, urand(20000, 25000)); - events.ScheduleEvent(EVENT_FIERY_COMBUSTION, urand(15000, 18000)); if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HALION_CONTROLLER))) controller->AI()->SetData(DATA_FIGHT_PHASE, PHASE_ONE); @@ -388,58 +298,76 @@ class boss_halion : public CreatureScript } } + void SpellHit(Unit* /*who*/, SpellInfo const* spellInfo) override + { + if (spellInfo->Id == SPELL_TWILIGHT_MENDING) + Talk(SAY_REGENERATE); + } + void UpdateAI(uint32 diff) override { if (events.IsInPhase(PHASE_TWO)) return; - generic_halionAI::UpdateAI(diff); - } + if (!UpdateVictim() || me->HasUnitState(UNIT_STATE_CASTING)) + return; - void ExecuteEvent(uint32 eventId) override - { - switch (eventId) + events.Update(diff); + + while (uint32 eventId = events.ExecuteEvent()) { - case EVENT_ACTIVATE_FIREWALL: - // Flame ring is activated 5 seconds after starting encounter, DOOR_TYPE_ROOM is only instant. - for (uint8 i = DATA_FLAME_RING; i <= DATA_TWILIGHT_FLAME_RING; ++i) - if (GameObject* flameRing = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(i))) - instance->HandleGameObject(instance->GetGuidData(DATA_FLAME_RING), false, flameRing); - break; - case EVENT_METEOR_STRIKE: + switch (eventId) { - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true, -SPELL_TWILIGHT_REALM)) + case EVENT_CLEAVE: + DoCastVictim(SPELL_CLEAVE); + events.ScheduleEvent(EVENT_CLEAVE, randtime(Seconds(8), Seconds(10))); + break; + case EVENT_TAIL_LASH: + DoCastAOE(SPELL_TAIL_LASH); + events.ScheduleEvent(EVENT_TAIL_LASH, randtime(Seconds(11), Seconds(16))); + break; + case EVENT_BREATH: + DoCast(me, SPELL_FLAME_BREATH); + events.ScheduleEvent(EVENT_BREATH, randtime(Seconds(16), Seconds(25))); + break; + case EVENT_ACTIVATE_FIREWALL: + // Flame ring is activated 5 seconds after starting encounter, DOOR_TYPE_ROOM is only instant. + for (uint8 i = DATA_FLAME_RING; i <= DATA_TWILIGHT_FLAME_RING; ++i) + if (GameObject* flameRing = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(i))) + instance->HandleGameObject(instance->GetGuidData(DATA_FLAME_RING), false, flameRing); + break; + case EVENT_METEOR_STRIKE: { - _meteorStrikePos = target->GetPosition(); - me->CastSpell(_meteorStrikePos.GetPositionX(), _meteorStrikePos.GetPositionY(), _meteorStrikePos.GetPositionZ(), SPELL_METEOR_STRIKE, true, NULL, NULL, me->GetGUID()); - Talk(SAY_METEOR_STRIKE); + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true, -SPELL_TWILIGHT_REALM)) + { + _meteorStrikePos = target->GetPosition(); + me->CastSpell(_meteorStrikePos.GetPositionX(), _meteorStrikePos.GetPositionY(), _meteorStrikePos.GetPositionZ(), SPELL_METEOR_STRIKE, true, nullptr, nullptr, me->GetGUID()); + Talk(SAY_METEOR_STRIKE); + } + events.ScheduleEvent(EVENT_METEOR_STRIKE, Seconds(38)); + break; } - events.ScheduleEvent(EVENT_METEOR_STRIKE, 40000); - break; - } - case EVENT_FIERY_COMBUSTION: - { - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, -SPELL_TWILIGHT_REALM)) - DoCast(target, SPELL_FIERY_COMBUSTION); - events.ScheduleEvent(EVENT_FIERY_COMBUSTION, 25000); - break; + case EVENT_FIERY_COMBUSTION: + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, -SPELL_TWILIGHT_REALM)) + me->CastSpell(target, SPELL_FIERY_COMBUSTION, TRIGGERED_IGNORE_SET_FACING); + events.ScheduleEvent(EVENT_FIERY_COMBUSTION, Seconds(25)); + break; + } + default: + break; } - default: - generic_halionAI::ExecuteEvent(eventId); - break; } + + DoMeleeAttackIfReady(); } void SetData(uint32 index, uint32 value) override { - switch (index) - { - case DATA_FIGHT_PHASE: - events.SetPhase(value); - break; - default: - generic_halionAI::SetData(index, value); - } + if (index != DATA_FIGHT_PHASE) + return; + + events.SetPhase(value); } private: @@ -459,9 +387,9 @@ class boss_twilight_halion : public CreatureScript public: boss_twilight_halion() : CreatureScript("boss_twilight_halion") { } - struct boss_twilight_halionAI : public generic_halionAI + struct boss_twilight_halionAI : public BossAI { - boss_twilight_halionAI(Creature* creature) : generic_halionAI(creature, DATA_TWILIGHT_HALION) + boss_twilight_halionAI(Creature* creature) : BossAI(creature, DATA_TWILIGHT_HALION) { Creature* halion = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HALION)); if (!halion) @@ -470,26 +398,29 @@ class boss_twilight_halion : public CreatureScript // Using AddAura because no spell cast packet in sniffs. halion->AddAura(SPELL_COPY_DAMAGE, me); // We use explicit targeting here to avoid conditions + SPELL_ATTR6_CANT_TARGET_SELF. me->AddAura(SPELL_COPY_DAMAGE, halion); - me->AddAura(SPELL_DUSK_SHROUD, me); + DoCast(me, SPELL_DUSK_SHROUD, true); me->SetHealth(halion->GetHealth()); me->SetPhaseMask(0x20, true); - me->SetReactState(REACT_AGGRESSIVE); + me->SetReactState(REACT_DEFENSIVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); + events.ScheduleEvent(EVENT_TAIL_LASH, Seconds(12)); + events.ScheduleEvent(EVENT_SOUL_CONSUMPTION, Seconds(15)); } - void EnterCombat(Unit* who) override + void EnterCombat(Unit* /*who*/) override { - events.Reset(); events.SetPhase(PHASE_TWO); - generic_halionAI::EnterCombat(who); - - events.ScheduleEvent(EVENT_SOUL_CONSUMPTION, 20000); + _EnterCombat(); + me->AddAura(SPELL_TWILIGHT_PRECISION, me); + events.ScheduleEvent(EVENT_CLEAVE, Seconds(3)); + events.ScheduleEvent(EVENT_BREATH, Seconds(12)); instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me, 2); } - // Never evade + void Reset() override { } void EnterEvadeMode(EvadeReason /*why*/) override { } void KilledUnit(Unit* victim) override @@ -522,6 +453,10 @@ class boss_twilight_halion : public CreatureScript void DamageTaken(Unit* attacker, uint32& damage) override { + //Needed because we already have UNIT_FLAG_IN_COMBAT, otherwise EnterCombat won't ever be called + if (!events.IsInPhase(PHASE_TWO) && !events.IsInPhase(PHASE_THREE)) + EnterCombat(attacker); + if (me->HealthBelowPctDamaged(50, damage) && events.IsInPhase(PHASE_TWO)) { events.SetPhase(PHASE_THREE); @@ -542,7 +477,7 @@ class boss_twilight_halion : public CreatureScript } } - void SpellHit(Unit* who, SpellInfo const* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { switch (spell->Id) { @@ -550,25 +485,51 @@ class boss_twilight_halion : public CreatureScript if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HALION_CONTROLLER))) controller->AI()->DoAction(ACTION_MONITOR_CORPOREALITY); break; + case SPELL_TWILIGHT_MENDING: + Talk(SAY_REGENERATE); + break; default: - generic_halionAI::SpellHit(who, spell); break; } } - void ExecuteEvent(uint32 eventId) override + void UpdateAI(uint32 diff) override { - switch (eventId) + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + if (!UpdateVictim()) + return; + + events.Update(diff); + + while (uint32 eventId = events.ExecuteEvent()) { - case EVENT_SOUL_CONSUMPTION: - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, SPELL_TWILIGHT_REALM)) - DoCast(target, SPELL_SOUL_CONSUMPTION); - events.ScheduleEvent(EVENT_SOUL_CONSUMPTION, 20000); - break; - default: - generic_halionAI::ExecuteEvent(eventId); - break; + switch (eventId) + { + case EVENT_CLEAVE: + DoCastVictim(SPELL_CLEAVE); + events.ScheduleEvent(EVENT_CLEAVE, randtime(Seconds(7), Seconds(10))); + break; + case EVENT_TAIL_LASH: + DoCastAOE(SPELL_TAIL_LASH); + events.ScheduleEvent(EVENT_TAIL_LASH, randtime(Seconds(12), Seconds(16))); + break; + case EVENT_BREATH: + DoCast(me, SPELL_DARK_BREATH); + events.ScheduleEvent(EVENT_BREATH, randtime(Seconds(10), Seconds(14))); + break; + case EVENT_SOUL_CONSUMPTION: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, SPELL_TWILIGHT_REALM)) + me->CastSpell(target, SPELL_SOUL_CONSUMPTION, TRIGGERED_IGNORE_SET_FACING); + events.ScheduleEvent(EVENT_SOUL_CONSUMPTION, Seconds(20)); + break; + default: + break; + } } + + DoMeleeAttackIfReady(); } }; @@ -589,7 +550,6 @@ class npc_halion_controller : public CreatureScript _instance(creature->GetInstanceScript()), _summons(me) { Initialize(); - me->SetPhaseMask(me->GetPhaseMask() | 0x20, true); } void Initialize() @@ -599,6 +559,15 @@ class npc_halion_controller : public CreatureScript _twilightDamageTaken = 0; } + void JustRespawned() override + { + if (_instance->GetGuidData(DATA_HALION)) + return; + + Reset(); + me->GetMap()->SummonCreature(NPC_HALION, HalionRespawnPos); + } + void Reset() override { _summons.DespawnAll(); @@ -626,21 +595,36 @@ class npc_halion_controller : public CreatureScript _twilightDamageTaken = 0; _materialDamageTaken = 0; - _events.ScheduleEvent(EVENT_TRIGGER_BERSERK, 8 * MINUTE * IN_MILLISECONDS); + _events.ScheduleEvent(EVENT_TRIGGER_BERSERK, Minutes(8)); } - void JustReachedHome() override + void EnterEvadeMode(EvadeReason /*why*/) override { if (Creature* twilightHalion = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_TWILIGHT_HALION))) + { twilightHalion->DespawnOrUnsummon(); + _instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, twilightHalion); + } if (Creature* halion = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_HALION))) { - halion->AI()->SetData(DATA_EVADE_METHOD, 1); - halion->AI()->EnterEvadeMode(); + halion->DespawnOrUnsummon(); + _instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, halion); } _instance->SetBossState(DATA_HALION, FAIL); + _summons.DespawnAll(); + + uint32 corpseDelay = me->GetCorpseDelay(); + uint32 respawnDelay = me->GetRespawnDelay(); + + me->SetCorpseDelay(1); + me->SetRespawnDelay(30); + + me->DespawnOrUnsummon(); + + me->SetCorpseDelay(corpseDelay); + me->SetRespawnDelay(respawnDelay); } void DoAction(int32 action) override @@ -650,7 +634,16 @@ class npc_halion_controller : public CreatureScript case ACTION_INTRO_HALION: _events.Reset(); _events.SetPhase(PHASE_INTRO); - _events.ScheduleEvent(EVENT_START_INTRO, 2000); + _events.ScheduleEvent(EVENT_START_INTRO, Seconds(2)); + break; + case ACTION_INTRO_HALION_2: + if (_instance->GetGuidData(DATA_HALION)) + return; + + for (uint8 i = DATA_BURNING_TREE_1; i <= DATA_BURNING_TREE_4; ++i) + if (GameObject* tree = ObjectAccessor::GetGameObject(*me, _instance->GetGuidData(i))) + _instance->HandleGameObject(_instance->GetGuidData(i), true, tree); + me->GetMap()->SummonCreature(NPC_HALION, HalionRespawnPos); break; case ACTION_MONITOR_CORPOREALITY: { @@ -678,8 +671,12 @@ class npc_halion_controller : public CreatureScript _instance->DoUpdateWorldState(WORLDSTATE_CORPOREALITY_MATERIAL, 50); _instance->DoUpdateWorldState(WORLDSTATE_CORPOREALITY_TWILIGHT, 50); - _events.ScheduleEvent(EVENT_CHECK_CORPOREALITY, 7500); + _events.ScheduleEvent(EVENT_CHECK_CORPOREALITY, Seconds(7)); + break; } + case ACTION_ACTIVATE_EMBERS: + _events.ScheduleEvent(EVENT_ACTIVATE_EMBERS, Seconds(6)); + break; default: break; } @@ -692,7 +689,7 @@ class npc_halion_controller : public CreatureScript // combat state. if (!_events.IsInPhase(PHASE_INTRO) && me->IsInCombat() && !UpdateVictim()) { - EnterEvadeMode(); + EnterEvadeMode(EVADE_REASON_NO_HOSTILES); return; } @@ -704,29 +701,31 @@ class npc_halion_controller : public CreatureScript { case EVENT_START_INTRO: DoCast(me, SPELL_COSMETIC_FIRE_PILLAR, true); - _events.ScheduleEvent(EVENT_INTRO_PROGRESS_1, 4000); + _events.ScheduleEvent(EVENT_INTRO_PROGRESS_1, Seconds(4)); break; case EVENT_INTRO_PROGRESS_1: for (uint8 i = DATA_BURNING_TREE_3; i <= DATA_BURNING_TREE_4; ++i) if (GameObject* tree = ObjectAccessor::GetGameObject(*me, _instance->GetGuidData(i))) _instance->HandleGameObject(_instance->GetGuidData(i), true, tree); - _events.ScheduleEvent(EVENT_INTRO_PROGRESS_2, 4000); + _events.ScheduleEvent(EVENT_INTRO_PROGRESS_2, Seconds(4)); break; case EVENT_INTRO_PROGRESS_2: for (uint8 i = DATA_BURNING_TREE_1; i <= DATA_BURNING_TREE_2; ++i) if (GameObject* tree = ObjectAccessor::GetGameObject(*me, _instance->GetGuidData(i))) _instance->HandleGameObject(_instance->GetGuidData(i), true, tree); - _events.ScheduleEvent(EVENT_INTRO_PROGRESS_3, 4000); + _events.ScheduleEvent(EVENT_INTRO_PROGRESS_3, Seconds(4)); break; case EVENT_INTRO_PROGRESS_3: DoCast(me, SPELL_FIERY_EXPLOSION); + if (_instance->GetGuidData(DATA_HALION)) + return; if (Creature* halion = me->GetMap()->SummonCreature(NPC_HALION, HalionSpawnPos)) halion->AI()->Talk(SAY_INTRO); break; case EVENT_TWILIGHT_MENDING: if (ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_HALION))) // Just check if physical Halion is spawned if (Creature* twilightHalion = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_TWILIGHT_HALION))) - twilightHalion->CastSpell((Unit*)NULL, SPELL_TWILIGHT_MENDING, true); + twilightHalion->CastSpell((Unit*)nullptr, SPELL_TWILIGHT_MENDING, true); break; case EVENT_TRIGGER_BERSERK: for (uint8 i = DATA_HALION; i <= DATA_TWILIGHT_HALION; i++) @@ -734,17 +733,16 @@ class npc_halion_controller : public CreatureScript halion->CastSpell(halion, SPELL_BERSERK, true); break; case EVENT_SHADOW_PULSARS_SHOOT: - if (Creature* twilightHalion = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_TWILIGHT_HALION))) - twilightHalion->AI()->Talk(SAY_SPHERE_PULSE); - if (Creature* orbCarrier = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ORB_CARRIER))) - orbCarrier->AI()->DoAction(ACTION_SHOOT); - - _events.ScheduleEvent(EVENT_SHADOW_PULSARS_SHOOT, 29000); + orbCarrier->AI()->DoAction(ACTION_WARNING_SHOOT); + _events.ScheduleEvent(EVENT_SHADOW_PULSARS_SHOOT, Seconds(30)); break; case EVENT_CHECK_CORPOREALITY: UpdateCorporeality(); - _events.ScheduleEvent(EVENT_CHECK_CORPOREALITY, 5000); + _events.ScheduleEvent(EVENT_CHECK_CORPOREALITY, Seconds(5)); + break; + case EVENT_ACTIVATE_EMBERS: + _summons.DoZoneInCombat(NPC_LIVING_EMBER); break; default: break; @@ -770,7 +768,7 @@ class npc_halion_controller : public CreatureScript DoZoneInCombat(); break; case PHASE_TWO: - _events.ScheduleEvent(EVENT_SHADOW_PULSARS_SHOOT, 29000); + _events.ScheduleEvent(EVENT_SHADOW_PULSARS_SHOOT, Seconds(35)); break; default: break; @@ -793,7 +791,7 @@ class npc_halion_controller : public CreatureScript uint8 oldValue = _materialCorporealityValue; if (_twilightDamageTaken == 0 || _materialDamageTaken == 0) { - _events.ScheduleEvent(EVENT_TWILIGHT_MENDING, 100); + _events.ScheduleEvent(EVENT_TWILIGHT_MENDING, Milliseconds(100)); _twilightDamageTaken = 0; _materialDamageTaken = 0; return; @@ -833,7 +831,7 @@ class npc_halion_controller : public CreatureScript } case CORPOREALITY_TWILIGHT_MENDING: { - _events.ScheduleEvent(EVENT_TWILIGHT_MENDING, 100); + _events.ScheduleEvent(EVENT_TWILIGHT_MENDING, Milliseconds(100)); _materialDamageTaken = 0; _twilightDamageTaken = 0; return; @@ -889,52 +887,73 @@ class npc_orb_carrier : public CreatureScript struct npc_orb_carrierAI : public ScriptedAI { npc_orb_carrierAI(Creature* creature) : ScriptedAI(creature), - instance(creature->GetInstanceScript()) + _instance(creature->GetInstanceScript()) { ASSERT(creature->GetVehicleKit()); } - void UpdateAI(uint32 /*diff*/) override + void UpdateAI(uint32 diff) override { /// According to sniffs this spell is cast every 1 or 2 seconds. /// However, refreshing it looks bad, so just cast the spell if /// we are not channeling it. if (!me->HasUnitState(UNIT_STATE_CASTING)) - me->CastSpell((Unit*)NULL, SPELL_TRACK_ROTATION, false); + me->CastSpell((Unit*)nullptr, SPELL_TRACK_ROTATION, false); + + scheduler.Update(diff); /// Workaround: This is here because even though the above spell has SPELL_ATTR1_CHANNEL_TRACK_TARGET, /// we are having two creatures involded here. This attribute is handled clientside, meaning the client /// sends orientation update itself. Here, no packet is sent, and the creature does not rotate. By /// forcing the carrier to always be facing the rotation focus, we ensure everything works as it should. - if (Creature* rotationFocus = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_ORB_ROTATION_FOCUS))) + if (Creature* rotationFocus = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ORB_ROTATION_FOCUS))) me->SetFacingToObject(rotationFocus); // setInFront } void DoAction(int32 action) override { - if (action == ACTION_SHOOT) + switch (action) { - Vehicle* vehicle = me->GetVehicleKit(); - Unit* southOrb = vehicle->GetPassenger(SEAT_SOUTH); - Unit* northOrb = vehicle->GetPassenger(SEAT_NORTH); - if (southOrb && northOrb) + case ACTION_WARNING_SHOOT: { - if (northOrb->GetTypeId() == TYPEID_UNIT) + Vehicle* vehicle = me->GetVehicleKit(); + Unit* northOrb = vehicle->GetPassenger(SEAT_NORTH); + if (northOrb && northOrb->GetTypeId() == TYPEID_UNIT) northOrb->ToCreature()->AI()->Talk(EMOTE_WARN_LASER); - TriggerCutter(northOrb, southOrb); + + scheduler.Schedule(Seconds(5), [this](TaskContext /*context*/) + { + DoAction(ACTION_SHOOT); + }); + break; } + case ACTION_SHOOT: + { + Vehicle* vehicle = me->GetVehicleKit(); + Unit* southOrb = vehicle->GetPassenger(SEAT_SOUTH); + Unit* northOrb = vehicle->GetPassenger(SEAT_NORTH); + if (southOrb && northOrb) + TriggerCutter(northOrb, southOrb); - if (!IsHeroic()) - return; + if (Creature* twilightHalion = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_TWILIGHT_HALION))) + twilightHalion->AI()->Talk(SAY_SPHERE_PULSE); + + if (!IsHeroic()) + return; - Unit* eastOrb = vehicle->GetPassenger(SEAT_EAST); - Unit* westOrb = vehicle->GetPassenger(SEAT_WEST); - if (eastOrb && westOrb) - TriggerCutter(eastOrb, westOrb); + Unit* eastOrb = vehicle->GetPassenger(SEAT_EAST); + Unit* westOrb = vehicle->GetPassenger(SEAT_WEST); + if (eastOrb && westOrb) + TriggerCutter(eastOrb, westOrb); + break; + } + default: + break; } } private: - InstanceScript* instance; + InstanceScript* _instance; + TaskScheduler scheduler; void TriggerCutter(Unit* caster, Unit* target) { @@ -987,12 +1006,12 @@ class npc_meteor_strike_initial : public CreatureScript controller->AI()->JustSummoned(me); DoCast(me, SPELL_METEOR_STRIKE_COUNTDOWN); - DoCast(me, SPELL_BIRTH_NO_VISUAL); // Unknown purpose + DoCast(me, SPELL_BIRTH_NO_VISUAL); if (HalionAI* halionAI = CAST_AI(HalionAI, owner->AI())) { Position const* ownerPos = halionAI->GetMeteorStrikePosition(); - float randomAdjustment = frand(0.0f, static_cast<float>(M_PI / 5.0f)); + float randomAdjustment = frand(static_cast<float>(M_PI / 5.0f), static_cast<float>(M_PI / 2.0f)); float angle[4]; angle[0] = me->GetAngle(ownerPos); angle[1] = angle[0] + randomAdjustment; @@ -1006,10 +1025,7 @@ class npc_meteor_strike_initial : public CreatureScript me->SetOrientation(angle[i]); Position newPos = me->GetNearPosition(10.0f, 0.0f); // Exact distance if (Creature* meteor = me->SummonCreature(NPC_METEOR_STRIKE_NORTH + i, newPos, TEMPSUMMON_TIMED_DESPAWN, 30000)) - { - meteor->SetOrientation(angle[i]); _meteorList.push_back(meteor); - } } } } @@ -1046,7 +1062,7 @@ class npc_meteor_strike : public CreatureScript { DoCast(me, SPELL_METEOR_STRIKE_FIRE_AURA_2, true); me->setActive(true); - _events.ScheduleEvent(EVENT_SPAWN_METEOR_FLAME, 500); + _events.ScheduleEvent(EVENT_SPAWN_METEOR_FLAME, Milliseconds(500)); } } @@ -1110,7 +1126,7 @@ class npc_meteor_strike_flame : public CreatureScript void SetGUID(ObjectGuid guid, int32 /*id = 0 */) override { _rootOwnerGuid = guid; - _events.ScheduleEvent(EVENT_SPAWN_METEOR_FLAME, 800); + _events.ScheduleEvent(EVENT_SPAWN_METEOR_FLAME, Milliseconds(800)); } void IsSummonedBy(Unit* /*summoner*/) override @@ -1202,7 +1218,7 @@ class npc_combustion_consumption : public CreatureScript if (type != DATA_STACKS_DISPELLED || !_damageSpell || !_explosionSpell || !summoner) return; - me->CastCustomSpell(SPELL_SCALE_AURA, SPELLVALUE_AURA_STACK, stackAmount, me); + me->CastCustomSpell(SPELL_SCALE_AURA, SPELLVALUE_AURA_STACK, stackAmount + 1, me); DoCast(me, _damageSpell); int32 damage = 1200 + (stackAmount * 1290); // Needs more research. @@ -1240,17 +1256,32 @@ class npc_living_inferno : public CreatureScript // SMSG_SPELL_GO for the living ember stuff isn't even sent to the client - Blizzard on drugs. if (me->GetMap()->GetDifficulty() == RAID_DIFFICULTY_25MAN_HEROIC) - me->CastSpell(me, SPELL_SPAWN_LIVING_EMBERS, true); + scheduler.Schedule(Seconds(3), [this](TaskContext /*context*/) + { + me->CastSpell(me, SPELL_SPAWN_LIVING_EMBERS, true); + }); if (InstanceScript* instance = me->GetInstanceScript()) if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HALION_CONTROLLER))) + { + controller->AI()->DoAction(ACTION_ACTIVATE_EMBERS); controller->AI()->JustSummoned(me); + } } void JustDied(Unit* /*killer*/) override { me->DespawnOrUnsummon(1); } + + void UpdateAI(uint32 diff) override + { + scheduler.Update(diff); + ScriptedAI::UpdateAI(diff); + } + + private: + TaskScheduler scheduler; }; CreatureAI* GetAI(Creature* creature) const override @@ -1266,27 +1297,7 @@ class npc_living_ember : public CreatureScript struct npc_living_emberAI : public ScriptedAI { - npc_living_emberAI(Creature* creature) : ScriptedAI(creature) - { - Initialize(); - _enrageTimer = 0; - } - - void Initialize() - { - _hasEnraged = false; - } - - void Reset() override - { - Initialize(); - } - - void EnterCombat(Unit* /*who*/) override - { - _enrageTimer = 20000; - _hasEnraged = false; - } + npc_living_emberAI(Creature* creature) : ScriptedAI(creature) { } void IsSummonedBy(Unit* /*summoner*/) override { @@ -1299,25 +1310,6 @@ class npc_living_ember : public CreatureScript { me->DespawnOrUnsummon(1); } - - void UpdateAI(uint32 diff) override - { - if (!UpdateVictim() || me->HasUnitState(UNIT_STATE_CASTING)) - return; - - if (!_hasEnraged && _enrageTimer <= diff) - { - _hasEnraged = true; - DoCast(me, SPELL_BERSERK); - } - else _enrageTimer -= diff; - - DoMeleeAttackIfReady(); - } - - private: - uint32 _enrageTimer; - bool _hasEnraged; }; CreatureAI* GetAI(Creature* creature) const override @@ -1473,6 +1465,47 @@ class spell_halion_combustion_consumption : public SpellScriptLoader uint32 _spellID; }; +class spell_halion_combustion_consumption_periodic : public SpellScriptLoader +{ + public: + spell_halion_combustion_consumption_periodic() : SpellScriptLoader("spell_halion_combustion_consumption_periodic") { } + + class spell_halion_combustion_consumption_periodic_AuraScript : public AuraScript + { + PrepareAuraScript(spell_halion_combustion_consumption_periodic_AuraScript); + + bool Validate(SpellInfo const* spellInfo) override + { + if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) + return false; + return true; + } + + void HandleTick(AuraEffect const* aurEff) + { + PreventDefaultAction(); + Unit* caster = GetCaster(); + if (!caster) + return; + + uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; + int32 radius = caster->GetObjectScale() * M_PI * 10000 / 3; + + caster->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, radius, (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff, caster->GetGUID()); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_halion_combustion_consumption_periodic_AuraScript::HandleTick, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_halion_combustion_consumption_periodic_AuraScript(); + } +}; + class spell_halion_marks : public SpellScriptLoader { public: @@ -1511,7 +1544,7 @@ class spell_halion_marks : public SpellScriptLoader return; // Stacks marker - GetTarget()->CastCustomSpell(_summonSpellId, SPELLVALUE_BASE_POINT1, aurEff->GetBase()->GetStackAmount(), GetTarget(), TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(_summonSpellId, SPELLVALUE_BASE_POINT1, aurEff->GetBase()->GetStackAmount(), GetTarget(), TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); } void Register() override @@ -1819,6 +1852,35 @@ class spell_halion_spawn_living_embers : public SpellScriptLoader } }; +class spell_halion_blazing_aura : public SpellScriptLoader +{ + public: + spell_halion_blazing_aura() : SpellScriptLoader("spell_halion_blazing_aura") { } + + class spell_halion_blazing_aura_SpellScript : public SpellScript + { + PrepareSpellScript(spell_halion_blazing_aura_SpellScript); + + void HandleScript(SpellEffIndex effIndex) + { + PreventHitDefaultEffect(effIndex); + GetHitUnit()->CastSpell(GetHitUnit(), GetSpellInfo()->Effects[EFFECT_1].TriggerSpell); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_halion_blazing_aura_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_FORCE_CAST); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_halion_blazing_aura_SpellScript(); + } +}; + + + void AddSC_boss_halion() { new boss_halion(); @@ -1840,6 +1902,7 @@ void AddSC_boss_halion() new spell_halion_combustion_consumption("spell_halion_fiery_combustion", SPELL_MARK_OF_COMBUSTION); new spell_halion_marks("spell_halion_mark_of_combustion", SPELL_FIERY_COMBUSTION_SUMMON, SPELL_FIERY_COMBUSTION); new spell_halion_marks("spell_halion_mark_of_consumption", SPELL_SOUL_CONSUMPTION_SUMMON, SPELL_SOUL_CONSUMPTION); + new spell_halion_combustion_consumption_periodic(); new spell_halion_damage_aoe_summon(); new spell_halion_twilight_realm_handlers("spell_halion_leave_twilight_realm", SPELL_SOUL_CONSUMPTION, false); new spell_halion_twilight_realm_handlers("spell_halion_enter_twilight_realm", SPELL_FIERY_COMBUSTION, true); @@ -1848,4 +1911,5 @@ void AddSC_boss_halion() new spell_halion_twilight_cutter(); new spell_halion_clear_debuffs(); new spell_halion_spawn_living_embers(); + new spell_halion_blazing_aura(); } diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp index a6cd8362db3..be85d3dc99c 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp @@ -23,7 +23,7 @@ #include "WorldPacket.h" #include "ruby_sanctum.h" -BossBoundaryData const boundaries = +BossBoundaryData const boundaries = { { DATA_GENERAL_ZARITHRIAN, new EllipseBoundary(Position(3013.409f, 529.492f), 45.0, 100.0) }, { DATA_HALION, new CircleBoundary(Position(3156.037f, 533.2656f), 48.5) } @@ -53,11 +53,11 @@ class instance_ruby_sanctum : public InstanceMapScript void OnPlayerEnter(Player* /*player*/) override { - if (!GetGuidData(DATA_HALION_CONTROLLER) && GetBossState(DATA_HALION) != DONE && GetBossState(DATA_GENERAL_ZARITHRIAN) == DONE) + if (!GetGuidData(DATA_HALION) && GetBossState(DATA_HALION) != DONE && GetBossState(DATA_GENERAL_ZARITHRIAN) == DONE) { instance->LoadGrid(HalionControllerSpawnPos.GetPositionX(), HalionControllerSpawnPos.GetPositionY()); - if (Creature* halionController = instance->SummonCreature(NPC_HALION_CONTROLLER, HalionControllerSpawnPos)) - halionController->AI()->DoAction(ACTION_INTRO_HALION); + if (Creature* halionController = instance->GetCreature(GetGuidData(DATA_HALION_CONTROLLER))) + halionController->AI()->DoAction(ACTION_INTRO_HALION_2); } } @@ -161,6 +161,12 @@ class instance_ruby_sanctum : public InstanceMapScript } } + void OnCreatureRemove(Creature* creature) override + { + if (creature->GetEntry() == NPC_HALION) + HalionGUID = ObjectGuid::Empty; + } + void OnUnitDeath(Unit* unit) override { Creature* creature = unit->ToCreature(); @@ -170,7 +176,7 @@ class instance_ruby_sanctum : public InstanceMapScript if (creature->GetEntry() == NPC_GENERAL_ZARITHRIAN && GetBossState(DATA_HALION) != DONE) { instance->LoadGrid(HalionControllerSpawnPos.GetPositionX(), HalionControllerSpawnPos.GetPositionY()); - if (Creature* halionController = instance->SummonCreature(NPC_HALION_CONTROLLER, HalionControllerSpawnPos)) + if (Creature* halionController = instance->GetCreature(GetGuidData(DATA_HALION_CONTROLLER))) halionController->AI()->DoAction(ACTION_INTRO_HALION); } } diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp index ae4a5e2a69a..9235b75d53e 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp @@ -18,6 +18,7 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "SpellScript.h" #include "ruby_sanctum.h" #include "Player.h" @@ -45,6 +46,11 @@ enum Events EVENT_XERESTRASZA_EVENT_7 = 7, }; +enum Spells +{ + SPELL_RALLY = 75416 +}; + Position const xerestraszaMovePos = {3151.236f, 379.8733f, 86.31996f, 0.0f}; class npc_xerestrasza : public CreatureScript @@ -165,8 +171,53 @@ class at_baltharus_plateau : public AreaTriggerScript } }; +// 75415 - Rallying Shout +class spell_ruby_sanctum_rallying_shout : public SpellScriptLoader +{ + public: + spell_ruby_sanctum_rallying_shout() : SpellScriptLoader("spell_ruby_sanctum_rallying_shout") { } + + class spell_ruby_sanctum_rallying_shout_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ruby_sanctum_rallying_shout_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_RALLY)) + return false; + return true; + } + + void CountTargets(std::list<WorldObject*>& targets) + { + _targetCount = targets.size(); + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + if (_targetCount && !GetCaster()->HasAura(SPELL_RALLY)) + GetCaster()->CastCustomSpell(SPELL_RALLY, SPELLVALUE_AURA_STACK, _targetCount, GetCaster(), TRIGGERED_FULL_MASK); + } + + void Register() override + { + OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ruby_sanctum_rallying_shout_SpellScript::CountTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY); + OnEffectHit += SpellEffectFn(spell_ruby_sanctum_rallying_shout_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + + private: + uint32 _targetCount = 0; + }; + + SpellScript* GetSpellScript() const override + { + return new spell_ruby_sanctum_rallying_shout_SpellScript(); + } +}; + void AddSC_ruby_sanctum() { new npc_xerestrasza(); new at_baltharus_plateau(); + new spell_ruby_sanctum_rallying_shout(); } diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h index 69c27a22ea0..333fef1dc85 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h @@ -56,6 +56,7 @@ enum SharedActions ACTION_INTRO_BALTHARUS = -3975101, ACTION_BALTHARUS_DEATH = -3975102, ACTION_INTRO_HALION = -4014601, + ACTION_INTRO_HALION_2 = -4014602, }; enum CreaturesIds diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp index 00900d440c9..f6726d60db3 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp @@ -180,7 +180,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); } } } @@ -203,7 +203,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); } break; case BOSS_ARGENT_CHALLENGE_P: @@ -212,7 +212,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, 0, 0, 0, 0, 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); } break; } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp index c89510211b9..dfe0cacdef7 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp @@ -222,10 +222,10 @@ class boss_anubarak_trial : public CreatureScript instance->SetBossState(BOSS_ANUBARAK, FAIL); //Summon Scarab Swarms neutral at random places for (int i = 0; i < 10; i++) - if (Creature* temp = me->SummonCreature(NPC_SCARAB, AnubarakLoc[1].GetPositionX()+urand(0, 50)-25, AnubarakLoc[1].GetPositionY()+urand(0, 50)-25, AnubarakLoc[1].GetPositionZ())) + if (Creature* scarab = me->SummonCreature(NPC_SCARAB, AnubarakLoc[1].GetPositionX()+urand(0, 50)-25, AnubarakLoc[1].GetPositionY()+urand(0, 50)-25, AnubarakLoc[1].GetPositionZ())) { - temp->setFaction(31); - temp->GetMotionMaster()->MoveRandom(10); + scarab->setFaction(31); + scarab->GetMotionMaster()->MoveRandom(10); } } @@ -804,7 +804,7 @@ class npc_anubarak_spike : public CreatureScript void StartChase(Unit* who) { DoCast(who, SPELL_MARK); - me->SetSpeed(MOVE_RUN, 0.5f); + me->SetSpeedRate(MOVE_RUN, 0.5f); // make sure the Spine will really follow the one he should me->getThreatManager().clearReferences(); me->SetInCombatWithZone(); @@ -881,9 +881,9 @@ class spell_anubarak_leeching_swarm : public SpellScriptLoader if (lifeLeeched < 250) lifeLeeched = 250; // Damage - caster->CastCustomSpell(target, SPELL_LEECHING_SWARM_DMG, &lifeLeeched, 0, 0, false); + caster->CastCustomSpell(target, SPELL_LEECHING_SWARM_DMG, &lifeLeeched, 0, 0, true); // Heal - caster->CastCustomSpell(caster, SPELL_LEECHING_SWARM_HEAL, &lifeLeeched, 0, 0, false); + caster->CastCustomSpell(caster, SPELL_LEECHING_SWARM_HEAL, &lifeLeeched, 0, 0, true); } } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp index 6c1b516c7de..ee44e1391b4 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp @@ -453,22 +453,22 @@ class boss_toc_champion_controller : public CreatureScript for (uint8 i = 0; i < vChampionEntries.size(); ++i) { uint8 pos = urand(0, vChampionJumpTarget.size()-1); - if (Creature* temp = me->SummonCreature(vChampionEntries[i], vChampionJumpOrigin[urand(0, vChampionJumpOrigin.size()-1)], TEMPSUMMON_MANUAL_DESPAWN)) + if (Creature* champion = me->SummonCreature(vChampionEntries[i], vChampionJumpOrigin[urand(0, vChampionJumpOrigin.size()-1)], TEMPSUMMON_MANUAL_DESPAWN)) { - _summons.Summon(temp); - temp->SetReactState(REACT_PASSIVE); - temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); + _summons.Summon(champion); + champion->SetReactState(REACT_PASSIVE); + champion->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); if (playerTeam == ALLIANCE) { - temp->SetHomePosition(vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), 0); - temp->GetMotionMaster()->MoveJump(vChampionJumpTarget[pos], 20.0f, 20.0f); - temp->SetOrientation(0); + champion->SetHomePosition(vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), 0); + champion->GetMotionMaster()->MoveJump(vChampionJumpTarget[pos], 20.0f, 20.0f); + champion->SetOrientation(0); } else { - temp->SetHomePosition((ToCCommonLoc[1].GetPositionX()*2)-vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), 3); - temp->GetMotionMaster()->MoveJump((ToCCommonLoc[1].GetPositionX() * 2) - vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), vChampionJumpTarget[pos].GetOrientation(), 20.0f, 20.0f); - temp->SetOrientation(3); + champion->SetHomePosition((ToCCommonLoc[1].GetPositionX()*2)-vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), 3); + champion->GetMotionMaster()->MoveJump((ToCCommonLoc[1].GetPositionX() * 2) - vChampionJumpTarget[pos].GetPositionX(), vChampionJumpTarget[pos].GetPositionY(), vChampionJumpTarget[pos].GetPositionZ(), vChampionJumpTarget[pos].GetOrientation(), 20.0f, 20.0f); + champion->SetOrientation(3); } } vChampionJumpTarget.erase(vChampionJumpTarget.begin()+pos); @@ -485,10 +485,10 @@ class boss_toc_champion_controller : public CreatureScript case 1: for (SummonList::iterator i = _summons.begin(); i != _summons.end(); ++i) { - if (Creature* temp = ObjectAccessor::GetCreature(*me, *i)) + if (Creature* summon = ObjectAccessor::GetCreature(*me, *i)) { - temp->SetReactState(REACT_AGGRESSIVE); - temp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); + summon->SetReactState(REACT_AGGRESSIVE); + summon->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); } } break; @@ -640,12 +640,12 @@ struct boss_faction_championsAI : public BossAI if (TeamInInstance == ALLIANCE) { - if (Creature* temp = ObjectAccessor::GetCreature(*me, instance->GetGuidData(NPC_VARIAN))) - temp->AI()->Talk(SAY_KILL_PLAYER); + if (Creature* varian = ObjectAccessor::GetCreature(*me, instance->GetGuidData(NPC_VARIAN))) + varian->AI()->Talk(SAY_KILL_PLAYER); } else - if (Creature* temp = ObjectAccessor::GetCreature(*me, instance->GetGuidData(NPC_GARROSH))) - temp->AI()->Talk(SAY_KILL_PLAYER); + if (Creature* garrosh = ObjectAccessor::GetCreature(*me, instance->GetGuidData(NPC_GARROSH))) + garrosh->AI()->Talk(SAY_KILL_PLAYER); } } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp index 2fba0c2af42..93823987d78 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp @@ -67,10 +67,12 @@ enum BossSpells SPELL_SHIVAN_SLASH = 67098, SPELL_SPINNING_STRIKE = 66283, SPELL_MISTRESS_KISS = 66336, - SPELL_FEL_INFERNO = 67047, - SPELL_FEL_STREAK = 66494, SPELL_LORD_HITTIN = 66326, // special effect preventing more specific spells be cast on the same player within 10 seconds - SPELL_MISTRESS_KISS_DAMAGE_SILENCE = 66359 + SPELL_MISTRESS_KISS_DAMAGE_SILENCE = 66359, + + // Felflame Infernal + SPELL_FEL_STREAK_VISUAL = 66493, + SPELL_FEL_STREAK = 66494, }; enum Events @@ -116,7 +118,7 @@ class boss_jaraxxus : public CreatureScript _JustReachedHome(); instance->SetBossState(BOSS_JARAXXUS, FAIL); DoCast(me, SPELL_JARAXXUS_CHAINS); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); } void KilledUnit(Unit* who) override @@ -305,18 +307,17 @@ class npc_fel_infernal : public CreatureScript { npc_fel_infernalAI(Creature* creature) : ScriptedAI(creature) { - Initialize(); _instance = creature->GetInstanceScript(); } - void Initialize() - { - _felStreakTimer = 30 * IN_MILLISECONDS; - } - void Reset() override { - Initialize(); + _scheduler.Schedule(Seconds(2), [this](TaskContext context) + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) + DoCast(target, SPELL_FEL_STREAK_VISUAL); + context.Repeat(Seconds(15)); + }); me->SetInCombatWithZone(); } @@ -328,23 +329,20 @@ class npc_fel_infernal : public CreatureScript return; } + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + if (!UpdateVictim()) return; - if (_felStreakTimer <= diff) + _scheduler.Update(diff, [this] { - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) - DoCast(target, SPELL_FEL_STREAK); - _felStreakTimer = 30*IN_MILLISECONDS; - } - else - _felStreakTimer -= diff; - - DoMeleeAttackIfReady(); + DoMeleeAttackIfReady(); + }); } private: - uint32 _felStreakTimer; InstanceScript* _instance; + TaskScheduler _scheduler; }; CreatureAI* GetAI(Creature* creature) const override @@ -579,6 +577,39 @@ class spell_mistress_kiss_area : public SpellScriptLoader } }; +class spell_fel_streak_visual : public SpellScriptLoader +{ +public: + spell_fel_streak_visual() : SpellScriptLoader("spell_fel_streak_visual") { } + + class spell_fel_streak_visual_SpellScript : public SpellScript + { + PrepareSpellScript(spell_fel_streak_visual_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_FEL_STREAK)) + return false; + return true; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + GetCaster()->CastSpell(GetHitUnit(), uint32(GetEffectValue()), true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_fel_streak_visual_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_fel_streak_visual_SpellScript(); + } +}; + void AddSC_boss_jaraxxus() { new boss_jaraxxus(); @@ -590,4 +621,5 @@ void AddSC_boss_jaraxxus() new spell_mistress_kiss(); new spell_mistress_kiss_area(); + new spell_fel_streak_visual(); } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp index e3720503d0a..b2283ec6fde 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp @@ -25,6 +25,7 @@ #include "Vehicle.h" #include "Player.h" #include "SpellScript.h" +#include "SpellAuraEffects.h" enum Yells { @@ -33,6 +34,7 @@ enum Yells // Acidmaw & Dreadscale EMOTE_ENRAGE = 0, + SAY_SPECIAL = 1, // Icehowl EMOTE_TRAMPLE_START = 0, @@ -78,22 +80,29 @@ enum BossSpells SPELL_FIRE_BOMB_DOT = 66318, SPELL_HEAD_CRACK = 66407, - //Acidmaw & Dreadscale + //Acidmaw & Dreadscale Generic + SPELL_SWEEP = 66794, + SUMMON_SLIME_POOL = 66883, + SPELL_EMERGE = 66947, + SPELL_SUBMERGE = 66948, + SPELL_ENRAGE = 68335, + SPELL_SLIME_POOL_EFFECT = 66882, //In 60s it diameter grows from 10y to 40y (r=r+0.25 per second) + SPELL_GROUND_VISUAL_0 = 66969, + SPELL_GROUND_VISUAL_1 = 68302, + SPELL_HATE_TO_ZERO = 63984, + //Acidmaw SPELL_ACID_SPIT = 66880, SPELL_PARALYTIC_SPRAY = 66901, - SPELL_ACID_SPEW = 66819, - SPELL_PARALYTIC_BITE = 66824, - SPELL_SWEEP_0 = 66794, - SUMMON_SLIME_POOL = 66883, - SPELL_FIRE_SPIT = 66796, + SPELL_PARALYTIC_BITE = 66824, //Paralytic Toxin + SPELL_ACID_SPEW = 66818, + SPELL_PARALYSIS = 66830, + SPELL_PARALYTIC_TOXIN = 66823, + //Dreadscale + SPELL_BURNING_BITE = 66879, // Burning Bile SPELL_MOLTEN_SPEW = 66821, - SPELL_BURNING_BITE = 66879, + SPELL_FIRE_SPIT = 66796, SPELL_BURNING_SPRAY = 66902, - SPELL_SWEEP_1 = 67646, - SPELL_EMERGE_0 = 66947, - SPELL_SUBMERGE_0 = 66948, - SPELL_ENRAGE = 68335, - SPELL_SLIME_POOL_EFFECT = 66882, //In 60s it diameter grows from 10y to 40y (r=r+0.25 per second) + SPELL_BURNING_BILE = 66869, //Icehowl SPELL_FEROCIOUS_BUTT = 66770, @@ -182,7 +191,7 @@ class boss_gormok : public CreatureScript { case 0: instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; @@ -549,7 +558,7 @@ struct boss_jormungarAI : public BossAI if (!Enraged && instance->GetData(TYPE_NORTHREND_BEASTS) == SNAKES_SPECIAL) { - me->RemoveAurasDueToSpell(SPELL_SUBMERGE_0); + me->RemoveAurasDueToSpell(SPELL_SUBMERGE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); DoCast(SPELL_ENRAGE); Enraged = true; @@ -586,10 +595,11 @@ struct boss_jormungarAI : public BossAI case EVENT_SUMMON_ACIDMAW: if (Creature* acidmaw = me->SummonCreature(NPC_ACIDMAW, ToCCommonLoc[9].GetPositionX(), ToCCommonLoc[9].GetPositionY(), ToCCommonLoc[9].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN)) { - acidmaw->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + acidmaw->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); acidmaw->SetReactState(REACT_AGGRESSIVE); acidmaw->SetInCombatWithZone(); - acidmaw->CastSpell(acidmaw, SPELL_EMERGE_0); + acidmaw->CastSpell(acidmaw, SPELL_EMERGE); + acidmaw->CastSpell(acidmaw, SPELL_GROUND_VISUAL_1, true); } return; case EVENT_SPRAY: @@ -598,7 +608,7 @@ struct boss_jormungarAI : public BossAI events.ScheduleEvent(EVENT_SPRAY, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); return; case EVENT_SWEEP: - DoCastAOE(SPELL_SWEEP_0); + DoCastAOE(SPELL_SWEEP); events.ScheduleEvent(EVENT_SWEEP, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); return; default: @@ -608,13 +618,14 @@ struct boss_jormungarAI : public BossAI if (events.IsInPhase(PHASE_MOBILE)) DoMeleeAttackIfReady(); if (events.IsInPhase(PHASE_STATIONARY)) - DoSpellAttackIfReady(SpitSpell); + DoCastVictim(SpitSpell); } void Submerge() { - DoCast(me, SPELL_SUBMERGE_0); - me->RemoveAurasDueToSpell(SPELL_EMERGE_0); + DoCast(me, SPELL_SUBMERGE); + DoCast(me, SPELL_GROUND_VISUAL_0, true); + me->RemoveAurasDueToSpell(SPELL_EMERGE); me->SetInCombatWithZone(); events.SetPhase(PHASE_SUBMERGED); events.ScheduleEvent(EVENT_EMERGE, 5*IN_MILLISECONDS, 0, PHASE_SUBMERGED); @@ -625,17 +636,20 @@ struct boss_jormungarAI : public BossAI void Emerge() { - DoCast(me, SPELL_EMERGE_0); + DoCast(me, SPELL_EMERGE); + DoCastAOE(SPELL_HATE_TO_ZERO, true); me->SetDisplayId(ModelMobile); - me->RemoveAurasDueToSpell(SPELL_SUBMERGE_0); + me->RemoveAurasDueToSpell(SPELL_SUBMERGE); + me->RemoveAurasDueToSpell(SPELL_GROUND_VISUAL_0); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); // if the worm was mobile before submerging, make him stationary now if (WasMobile) { - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(false); me->SetDisplayId(ModelStationary); + me->CastSpell(me, SPELL_GROUND_VISUAL_1, true); events.SetPhase(PHASE_STATIONARY); events.ScheduleEvent(EVENT_SUBMERGE, 45*IN_MILLISECONDS, 0, PHASE_STATIONARY); events.ScheduleEvent(EVENT_SPIT, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_STATIONARY); @@ -644,10 +658,11 @@ struct boss_jormungarAI : public BossAI } else { - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(true); me->GetMotionMaster()->MoveChase(me->GetVictim()); me->SetDisplayId(ModelMobile); + me->RemoveAurasDueToSpell(SPELL_GROUND_VISUAL_1); events.SetPhase(PHASE_MOBILE); events.ScheduleEvent(EVENT_SUBMERGE, 45*IN_MILLISECONDS, 0, PHASE_MOBILE); events.ScheduleEvent(EVENT_BITE, urand(15*IN_MILLISECONDS, 30*IN_MILLISECONDS), 0, PHASE_MOBILE); @@ -737,7 +752,7 @@ class boss_dreadscale : public CreatureScript { case 0: instance->DoCloseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; @@ -910,7 +925,7 @@ class boss_icehowl : public CreatureScript break; case 2: instance->DoUseDoorOrButton(instance->GetGuidData(GO_MAIN_GATE_DOOR)); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); break; @@ -1008,7 +1023,7 @@ class boss_icehowl : public CreatureScript me->SetTarget(_trampleTargetGUID); _trampleCast = false; SetCombatMovement(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveIdle(); events.ScheduleEvent(EVENT_TRAMPLE, 4*IN_MILLISECONDS); @@ -1092,7 +1107,7 @@ class boss_icehowl : public CreatureScript Talk(EMOTE_TRAMPLE_FAIL); } _movementStarted = false; - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); SetCombatMovement(true); me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->Clear(); @@ -1122,6 +1137,148 @@ class boss_icehowl : public CreatureScript } }; +class spell_jormungars_paralytic_toxin : public SpellScriptLoader +{ +public: + spell_jormungars_paralytic_toxin() : SpellScriptLoader("spell_jormungars_paralytic_toxin") { } + + class spell_jormungars_paralytic_toxin_AuraScript : public AuraScript + { + PrepareAuraScript(spell_jormungars_paralytic_toxin_AuraScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_PARALYSIS)) + return false; + return true; + } + + void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + Unit* caster = GetCaster(); + if (caster && caster->GetEntry() == NPC_ACIDMAW) + { + if (Creature* acidMaw = caster->ToCreature()) + acidMaw->AI()->Talk(SAY_SPECIAL, GetTarget()); + } + } + + void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + GetTarget()->RemoveAurasDueToSpell(SPELL_PARALYSIS); + } + + void CalculateAmount(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) + { + if (!canBeRecalculated) + amount = aurEff->GetAmount(); + + canBeRecalculated = false; + } + + void HandleDummy(AuraEffect const* /*aurEff*/) + { + if (AuraEffect* slowEff = GetEffect(EFFECT_0)) + { + int32 newAmount = slowEff->GetAmount() - 10; + if (newAmount < -100) + newAmount = -100; + slowEff->ChangeAmount(newAmount); + + if (newAmount <= -100 && !GetTarget()->HasAura(SPELL_PARALYSIS)) + GetTarget()->CastSpell(GetTarget(), SPELL_PARALYSIS, true, NULL, slowEff, GetCasterGUID()); + } + } + + void Register() override + { + AfterEffectApply += AuraEffectApplyFn(spell_jormungars_paralytic_toxin_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_DECREASE_SPEED, AURA_EFFECT_HANDLE_REAL); + AfterEffectRemove += AuraEffectRemoveFn(spell_jormungars_paralytic_toxin_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_DECREASE_SPEED, AURA_EFFECT_HANDLE_REAL); + DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_jormungars_paralytic_toxin_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_DECREASE_SPEED); + OnEffectPeriodic += AuraEffectPeriodicFn(spell_jormungars_paralytic_toxin_AuraScript::HandleDummy, EFFECT_2, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_jormungars_paralytic_toxin_AuraScript(); + } +}; + +class spell_jormungars_snakes_spray : public SpellScriptLoader +{ +public: + spell_jormungars_snakes_spray(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + + class spell_jormungars_snakes_spray_SpellScript : public SpellScript + { + PrepareSpellScript(spell_jormungars_snakes_spray_SpellScript); + + public: + spell_jormungars_snakes_spray_SpellScript(uint32 spellId) : SpellScript(), _spellId(spellId) { } + + bool Validate(SpellInfo const* /*spell*/) override + { + if (!sSpellMgr->GetSpellInfo(_spellId)) + return false; + return true; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + if (Player* target = GetHitPlayer()) + GetCaster()->CastSpell(target, _spellId, true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_jormungars_snakes_spray_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); + } + + private: + uint32 _spellId; + }; + + SpellScript* GetSpellScript() const override + { + return new spell_jormungars_snakes_spray_SpellScript(_spellId); + } + +private: + uint32 _spellId; +}; + +class spell_jormungars_paralysis : public SpellScriptLoader +{ +public: + spell_jormungars_paralysis() : SpellScriptLoader("spell_jormungars_paralysis") { } + + class spell_jormungars_paralysis_AuraScript : public AuraScript + { + PrepareAuraScript(spell_jormungars_paralysis_AuraScript); + + void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + if (Unit* caster = GetCaster()) + if (InstanceScript* instance = caster->GetInstanceScript()) + if (instance->GetData(TYPE_NORTHREND_BEASTS) == SNAKES_IN_PROGRESS || instance->GetData(TYPE_NORTHREND_BEASTS) == SNAKES_SPECIAL) + return; + + Remove(); + } + + void Register() override + { + AfterEffectApply += AuraEffectApplyFn(spell_jormungars_paralysis_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_STUN, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_jormungars_paralysis_AuraScript(); + } +}; + void AddSC_boss_northrend_beasts() { new boss_gormok(); @@ -1132,6 +1289,10 @@ void AddSC_boss_northrend_beasts() new boss_acidmaw(); new boss_dreadscale(); new npc_slime_pool(); + new spell_jormungars_paralytic_toxin(); + new spell_jormungars_snakes_spray("spell_jormungars_burning_spray", SPELL_BURNING_BILE); + new spell_jormungars_snakes_spray("spell_jormungars_paralytic_spray", SPELL_PARALYTIC_TOXIN); + new spell_jormungars_paralysis(); new boss_icehowl(); } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp index eb1e769c07e..c6ac59218ea 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp @@ -132,7 +132,7 @@ class OrbsDespawner : public BasicEvent { } - bool Execute(uint64 /*currTime*/, uint32 /*diff*/) + bool Execute(uint64 /*currTime*/, uint32 /*diff*/) override { Trinity::CreatureWorker<OrbsDespawner> worker(_creature, *this); _creature->VisitNearbyGridObject(5000.0f, worker); @@ -440,10 +440,8 @@ class boss_fjola : public CreatureScript // Allocate an unique random stage to each position in the array. for (int i = 0; i < MAX_STAGES - 1; ++i) { - int random = i + (rand32() % (MAX_STAGES - i)); - int temp = Stage[i]; - Stage[i] = Stage[random]; - Stage[random] = temp; + int random = i + urand(0, MAX_STAGES - i); + std::swap(Stage[i], Stage[random]); } } private: @@ -804,8 +802,8 @@ class spell_valkyr_essences : public SpellScriptLoader else { owner->CastSpell(owner, poweringUp, true); - if (Aura* pTemp = owner->GetAura(poweringUp)) - pTemp->ModStackAmount(stacksCount); + if ((pAura = owner->GetAura(poweringUp))) + pAura->ModStackAmount(stacksCount); } } } @@ -829,8 +827,8 @@ class spell_valkyr_essences : public SpellScriptLoader else { owner->CastSpell(owner, poweringUp, true); - if (Aura* pTemp = owner->GetAura(poweringUp)) - pTemp->ModStackAmount(stacksCount); + if ((pAura = owner->GetAura(poweringUp))) + pAura->ModStackAmount(stacksCount); } } } 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 b1a0f0217c4..eb4840f3b8b 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 @@ -314,7 +314,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript if (tributeChest) if (Creature* tirion = instance->GetCreature(TirionGUID)) - if (GameObject* chest = tirion->SummonGameObject(tributeChest, 805.62f, 134.87f, 142.16f, 3.27f, 0, 0, 0, 0, WEEK)) + if (GameObject* chest = tirion->SummonGameObject(tributeChest, 805.62f, 134.87f, 142.16f, 3.27f, G3D::Quat(), WEEK)) chest->SetRespawnTime(chest->GetRespawnDelay()); break; } diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp index 0ffe74932e0..8ea292d1de5 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp @@ -174,7 +174,7 @@ class npc_announcer_toc10 : public CreatureScript if (Creature* jaraxxus = ObjectAccessor::GetCreature(*player, instance->GetGuidData(NPC_JARAXXUS))) { jaraxxus->RemoveAurasDueToSpell(SPELL_JARAXXUS_CHAINS); - jaraxxus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + jaraxxus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); jaraxxus->SetReactState(REACT_DEFENSIVE); jaraxxus->SetInCombatWithZone(); } @@ -360,11 +360,11 @@ class npc_fizzlebang_toc : public CreatureScript { Talk(SAY_STAGE_1_06, killer); _instance->SetData(TYPE_EVENT, 1180); - if (Creature* temp = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) + if (Creature* jaraxxus = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) { - temp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - temp->SetReactState(REACT_AGGRESSIVE); - temp->SetInCombatWithZone(); + jaraxxus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); + jaraxxus->SetReactState(REACT_AGGRESSIVE); + jaraxxus->SetInCombatWithZone(); } } @@ -457,18 +457,18 @@ class npc_fizzlebang_toc : public CreatureScript break; case 1140: Talk(SAY_STAGE_1_04); - if (Creature* temp = me->SummonCreature(NPC_JARAXXUS, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 5.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) + if (Creature* jaraxxus = me->SummonCreature(NPC_JARAXXUS, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 5.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) { - temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - temp->SetReactState(REACT_PASSIVE); - temp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY()-10, ToCCommonLoc[1].GetPositionZ()); + jaraxxus->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC); + jaraxxus->SetReactState(REACT_PASSIVE); + jaraxxus->GetMotionMaster()->MovePoint(0, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY()-10, ToCCommonLoc[1].GetPositionZ()); } _instance->SetData(TYPE_EVENT, 1142); _updateTimer = 5*IN_MILLISECONDS; break; case 1142: - if (Creature* temp = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) - temp->SetTarget(me->GetGUID()); + if (Creature* jaraxxus = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) + jaraxxus->SetTarget(me->GetGUID()); if (Creature* pTrigger = ObjectAccessor::GetCreature(*me, _triggerGUID)) pTrigger->DespawnOrUnsummon(); if (Creature* pPortal = ObjectAccessor::GetCreature(*me, _portalGUID)) @@ -477,19 +477,19 @@ class npc_fizzlebang_toc : public CreatureScript _updateTimer = 10*IN_MILLISECONDS; break; case 1144: - if (Creature* temp = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) - temp->AI()->Talk(SAY_STAGE_1_05); + if (Creature* jaraxxus = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) + jaraxxus->AI()->Talk(SAY_STAGE_1_05); _instance->SetData(TYPE_EVENT, 1150); _updateTimer = 5*IN_MILLISECONDS; break; case 1150: - if (Creature* temp = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) + if (Creature* jaraxxus = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(NPC_JARAXXUS))) { //1-shot Fizzlebang - temp->CastSpell(me, 67888, false); - me->SetInCombatWith(temp); - temp->AddThreat(me, 1000.0f); - temp->AI()->AttackStart(me); + jaraxxus->CastSpell(me, 67888, false); // 67888 - Fel Lightning + me->SetInCombatWith(jaraxxus); + jaraxxus->AddThreat(me, 1000.0f); + jaraxxus->AI()->AttackStart(me); } _instance->SetData(TYPE_EVENT, 1160); _updateTimer = 3*IN_MILLISECONDS; @@ -561,11 +561,11 @@ class npc_tirion_toc : public CreatureScript { _instance->DoUseDoorOrButton(_instance->GetGuidData(GO_MAIN_GATE_DOOR)); - if (Creature* temp = me->SummonCreature(NPC_GORMOK, ToCSpawnLoc[0].GetPositionX(), ToCSpawnLoc[0].GetPositionY(), ToCSpawnLoc[0].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30*IN_MILLISECONDS)) + if (Creature* gormok = me->SummonCreature(NPC_GORMOK, ToCSpawnLoc[0].GetPositionX(), ToCSpawnLoc[0].GetPositionY(), ToCSpawnLoc[0].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30*IN_MILLISECONDS)) { - temp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); - temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); - temp->SetReactState(REACT_PASSIVE); + gormok->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); + gormok->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + gormok->SetReactState(REACT_PASSIVE); } } _updateTimer = 3*IN_MILLISECONDS; @@ -582,11 +582,11 @@ class npc_tirion_toc : public CreatureScript if (_instance->GetBossState(BOSS_BEASTS) != DONE) { _instance->DoUseDoorOrButton(_instance->GetGuidData(GO_MAIN_GATE_DOOR)); - if (Creature* temp = me->SummonCreature(NPC_DREADSCALE, ToCSpawnLoc[1].GetPositionX(), ToCSpawnLoc[1].GetPositionY(), ToCSpawnLoc[1].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN)) + if (Creature* dreadscale = me->SummonCreature(NPC_DREADSCALE, ToCSpawnLoc[1].GetPositionX(), ToCSpawnLoc[1].GetPositionY(), ToCSpawnLoc[1].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN)) { - temp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); - temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); - temp->SetReactState(REACT_PASSIVE); + dreadscale->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); + dreadscale->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + dreadscale->SetReactState(REACT_PASSIVE); } } _updateTimer = 5*IN_MILLISECONDS; @@ -600,9 +600,9 @@ class npc_tirion_toc : public CreatureScript if (_instance->GetBossState(BOSS_BEASTS) != DONE) { _instance->DoUseDoorOrButton(_instance->GetGuidData(GO_MAIN_GATE_DOOR)); - if (Creature* temp = me->SummonCreature(NPC_ICEHOWL, ToCSpawnLoc[0].GetPositionX(), ToCSpawnLoc[0].GetPositionY(), ToCSpawnLoc[0].GetPositionZ(), 5, TEMPSUMMON_DEAD_DESPAWN)) + if (Creature* icehowl = me->SummonCreature(NPC_ICEHOWL, ToCSpawnLoc[0].GetPositionX(), ToCSpawnLoc[0].GetPositionY(), ToCSpawnLoc[0].GetPositionZ(), 5, TEMPSUMMON_DEAD_DESPAWN)) { - temp->GetMotionMaster()->MovePoint(2, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); + icehowl->GetMotionMaster()->MovePoint(2, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); } @@ -698,34 +698,34 @@ class npc_tirion_toc : public CreatureScript break; case 4010: Talk(SAY_STAGE_3_02); - if (Creature* temp = me->SummonCreature(NPC_LIGHTBANE, ToCSpawnLoc[1].GetPositionX(), ToCSpawnLoc[1].GetPositionY(), ToCSpawnLoc[1].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) + if (Creature* lightbane = me->SummonCreature(NPC_LIGHTBANE, ToCSpawnLoc[1].GetPositionX(), ToCSpawnLoc[1].GetPositionY(), ToCSpawnLoc[1].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) { - temp->SetVisible(false); - temp->SetReactState(REACT_PASSIVE); - temp->SummonCreature(NPC_LIGHT_ESSENCE, TwinValkyrsLoc[0].GetPositionX(), TwinValkyrsLoc[0].GetPositionY(), TwinValkyrsLoc[0].GetPositionZ()); - temp->SummonCreature(NPC_LIGHT_ESSENCE, TwinValkyrsLoc[1].GetPositionX(), TwinValkyrsLoc[1].GetPositionY(), TwinValkyrsLoc[1].GetPositionZ()); + lightbane->SetVisible(false); + lightbane->SetReactState(REACT_PASSIVE); + lightbane->SummonCreature(NPC_LIGHT_ESSENCE, TwinValkyrsLoc[0].GetPositionX(), TwinValkyrsLoc[0].GetPositionY(), TwinValkyrsLoc[0].GetPositionZ()); + lightbane->SummonCreature(NPC_LIGHT_ESSENCE, TwinValkyrsLoc[1].GetPositionX(), TwinValkyrsLoc[1].GetPositionY(), TwinValkyrsLoc[1].GetPositionZ()); } - if (Creature* temp = me->SummonCreature(NPC_DARKBANE, ToCSpawnLoc[2].GetPositionX(), ToCSpawnLoc[2].GetPositionY(), ToCSpawnLoc[2].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) + if (Creature* darkbane = me->SummonCreature(NPC_DARKBANE, ToCSpawnLoc[2].GetPositionX(), ToCSpawnLoc[2].GetPositionY(), ToCSpawnLoc[2].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) { - temp->SetVisible(false); - temp->SetReactState(REACT_PASSIVE); - temp->SummonCreature(NPC_DARK_ESSENCE, TwinValkyrsLoc[2].GetPositionX(), TwinValkyrsLoc[2].GetPositionY(), TwinValkyrsLoc[2].GetPositionZ()); - temp->SummonCreature(NPC_DARK_ESSENCE, TwinValkyrsLoc[3].GetPositionX(), TwinValkyrsLoc[3].GetPositionY(), TwinValkyrsLoc[3].GetPositionZ()); + darkbane->SetVisible(false); + darkbane->SetReactState(REACT_PASSIVE); + darkbane->SummonCreature(NPC_DARK_ESSENCE, TwinValkyrsLoc[2].GetPositionX(), TwinValkyrsLoc[2].GetPositionY(), TwinValkyrsLoc[2].GetPositionZ()); + darkbane->SummonCreature(NPC_DARK_ESSENCE, TwinValkyrsLoc[3].GetPositionX(), TwinValkyrsLoc[3].GetPositionY(), TwinValkyrsLoc[3].GetPositionZ()); } _updateTimer = 3*IN_MILLISECONDS; _instance->SetData(TYPE_EVENT, 4015); break; case 4015: _instance->DoUseDoorOrButton(_instance->GetGuidData(GO_MAIN_GATE_DOOR)); - if (Creature* temp = ObjectAccessor::GetCreature((*me), _instance->GetGuidData(NPC_LIGHTBANE))) + if (Creature* lightbane = ObjectAccessor::GetCreature((*me), _instance->GetGuidData(NPC_LIGHTBANE))) { - temp->GetMotionMaster()->MovePoint(1, ToCCommonLoc[8].GetPositionX(), ToCCommonLoc[8].GetPositionY(), ToCCommonLoc[8].GetPositionZ()); - temp->SetVisible(true); + lightbane->GetMotionMaster()->MovePoint(1, ToCCommonLoc[8].GetPositionX(), ToCCommonLoc[8].GetPositionY(), ToCCommonLoc[8].GetPositionZ()); + lightbane->SetVisible(true); } - if (Creature* temp = ObjectAccessor::GetCreature((*me), _instance->GetGuidData(NPC_DARKBANE))) + if (Creature* darkbane = ObjectAccessor::GetCreature((*me), _instance->GetGuidData(NPC_DARKBANE))) { - temp->GetMotionMaster()->MovePoint(1, ToCCommonLoc[9].GetPositionX(), ToCCommonLoc[9].GetPositionY(), ToCCommonLoc[9].GetPositionZ()); - temp->SetVisible(true); + darkbane->GetMotionMaster()->MovePoint(1, ToCCommonLoc[9].GetPositionX(), ToCCommonLoc[9].GetPositionY(), ToCCommonLoc[9].GetPositionZ()); + darkbane->SetVisible(true); } _updateTimer = 10*IN_MILLISECONDS; _instance->SetData(TYPE_EVENT, 4016); @@ -754,9 +754,9 @@ class npc_tirion_toc : public CreatureScript _instance->SetData(TYPE_EVENT, 0); break; case 6000: - me->SummonCreature(NPC_TIRION_FORDRING, EndSpawnLoc[0].GetPositionX(), EndSpawnLoc[0].GetPositionY(), EndSpawnLoc[0].GetPositionZ()); - me->SummonCreature(NPC_ARGENT_MAGE, EndSpawnLoc[1].GetPositionX(), EndSpawnLoc[1].GetPositionY(), EndSpawnLoc[1].GetPositionZ()); - me->SummonGameObject(GO_PORTAL_TO_DALARAN, EndSpawnLoc[2].GetPositionX(), EndSpawnLoc[2].GetPositionY(), EndSpawnLoc[2].GetPositionZ(), 5, 0, 0, 0, 0, 0); + me->SummonCreature(NPC_TIRION_FORDRING, EndSpawnLoc[0]); + me->SummonCreature(NPC_ARGENT_MAGE, EndSpawnLoc[1]); + me->SummonGameObject(GO_PORTAL_TO_DALARAN, EndSpawnLoc[2], G3D::Quat(), 0); _updateTimer = 20*IN_MILLISECONDS; _instance->SetData(TYPE_EVENT, 6005); break; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h index 90b9781954f..d53d6705400 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h @@ -140,9 +140,9 @@ const Position AnubarakLoc[]= const Position EndSpawnLoc[]= { - {648.9167f, 131.0208f, 141.6161f, 0}, // 0 - Highlord Tirion Fordring - {649.1614f, 142.0399f, 141.3057f, 0}, // 1 - Argent Mage - {644.6250f, 149.2743f, 140.6015f, 0} // 2 - Portal to Dalaran + {648.9167f, 131.0208f, 141.6161f, 0.f}, // 0 - Highlord Tirion Fordring + {649.1614f, 142.0399f, 141.3057f, 0.f}, // 1 - Argent Mage + {644.6250f, 149.2743f, 140.6015f, 5.f} // 2 - Portal to Dalaran }; enum WorldStateIds diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp index ce722e391d1..292f1d7074f 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp @@ -198,8 +198,6 @@ public: { if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC)) - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); if (me->HasUnitState(UNIT_STATE_CASTING)) me->CastStop(); } @@ -207,8 +205,6 @@ public: { if (!me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - if (!me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC)) - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); DoCast(SPELL_ARCANE_FIELD); } } diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp index 055d0a07f41..94d1d93225c 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp @@ -144,7 +144,7 @@ class boss_devourer_of_souls : public CreatureScript void Reset() override { _Reset(); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->SetDisplayId(DISPLAY_ANGER); me->SetReactState(REACT_AGGRESSIVE); @@ -297,7 +297,7 @@ class boss_devourer_of_souls : public CreatureScript me->SetTarget(ObjectGuid::Empty); me->GetMotionMaster()->Clear(); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); wailingSoulTick = 15; events.DelayEvents(18000); // no other events during wailing souls @@ -317,7 +317,7 @@ class boss_devourer_of_souls : public CreatureScript { me->SetReactState(REACT_AGGRESSIVE); me->SetDisplayId(DISPLAY_ANGER); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->GetMotionMaster()->MoveChase(me->GetVictim()); events.ScheduleEvent(EVENT_WAILING_SOULS, urand(60000, 70000)); } diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp index 4c2b92da0ea..6b20ae6a373 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp @@ -1921,6 +1921,7 @@ class npc_frostsworn_general : public CreatureScript { if (Creature* reflection = me->SummonCreature(NPC_REFLECTION, *target, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 3000)) { + reflection->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); target->CastSpell(reflection, SPELL_CLONE, true); target->CastSpell(reflection, SPELL_GHOST_VISUAL, true); reflection->AI()->AttackStart(target); @@ -2155,6 +2156,7 @@ struct npc_escape_event_trash : public ScriptedAI DoZoneInCombat(me, 0.0f); if (Creature* leader = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ESCAPE_LEADER))) { + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); me->SetInCombatWith(leader); leader->SetInCombatWith(me); me->AddThreat(leader, 0.0f); @@ -2580,7 +2582,7 @@ class npc_quel_delar_sword : public CreatureScript void Reset() override { _events.Reset(); - me->SetSpeed(MOVE_FLIGHT, 4.5f, true); + me->SetSpeedRate(MOVE_FLIGHT, 4.5f); DoCast(SPELL_WHIRLWIND_VISUAL); if (_intro) _events.ScheduleEvent(EVENT_QUEL_DELAR_INIT, 0); diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp index 03f12e46bc3..b24a36da3fb 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp @@ -418,7 +418,7 @@ class boss_krick : public CreatureScript case EVENT_OUTRO_6: if (Creature* tyrannus = ObjectAccessor::GetCreature(*me, _instanceScript->GetGuidData(DATA_TYRANNUS_EVENT))) { - tyrannus->SetSpeed(MOVE_FLIGHT, 3.5f, true); + tyrannus->SetSpeedRate(MOVE_FLIGHT, 3.5f); tyrannus->GetMotionMaster()->MovePoint(1, outroPos[4]); _tyrannusGUID = tyrannus->GetGUID(); } diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp index 96bd0aaa35e..5410f403ab9 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp @@ -22,6 +22,7 @@ #include "pit_of_saron.h" #include "Vehicle.h" #include "Player.h" +#include "PlayerAI.h" enum Yells { @@ -438,9 +439,10 @@ class spell_tyrannus_overlord_brand : public SpellScriptLoader if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; - oldAI = GetTarget()->GetAI(); - oldAIState = GetTarget()->IsAIEnabled; - GetTarget()->SetAI(new player_overlord_brandAI(GetTarget()->ToPlayer(), GetCasterGUID())); + Player* pTarget = GetTarget()->ToPlayer(); + oldAI = pTarget->AI(); + oldAIState = pTarget->IsAIEnabled; + GetTarget()->SetAI(new player_overlord_brandAI(pTarget, GetCasterGUID())); GetTarget()->IsAIEnabled = true; } @@ -450,7 +452,7 @@ class spell_tyrannus_overlord_brand : public SpellScriptLoader return; GetTarget()->IsAIEnabled = oldAIState; - UnitAI* thisAI = GetTarget()->GetAI(); + PlayerAI* thisAI = GetTarget()->ToPlayer()->AI(); GetTarget()->SetAI(oldAI); delete thisAI; } @@ -461,7 +463,7 @@ class spell_tyrannus_overlord_brand : public SpellScriptLoader AfterEffectRemove += AuraEffectRemoveFn(spell_tyrannus_overlord_brand_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } - UnitAI* oldAI; + PlayerAI* oldAI; bool oldAIState; }; diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp index f59701b9c25..51711f9ded5 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp @@ -160,7 +160,7 @@ class StandUpEvent : public BasicEvent public: StandUpEvent(Creature& owner) : BasicEvent(), _owner(owner) { } - bool Execute(uint64 /*eventTime*/, uint32 /*diff*/) + bool Execute(uint64 /*eventTime*/, uint32 /*diff*/) override { _owner.HandleEmoteCommand(EMOTE_ONESHOT_ROAR); _owner.SetReactState(REACT_AGGRESSIVE); @@ -1069,7 +1069,7 @@ class npc_blood_queen_lana_thel : public CreatureScript if (Creature* summon = DoSummon(NPC_FLOATING_TRIGGER, triggerPos, 15000, TEMPSUMMON_TIMED_DESPAWN)) { summon->CastSpell(summon, SPELL_OOC_INVOCATION_VISUAL, true); - summon->SetSpeed(MOVE_FLIGHT, 0.15f, true); // todo: creature is swimming, check if this is blizzlike or not. + summon->SetSpeedRate(MOVE_FLIGHT, 0.15f); // todo: creature is swimming, check if this is blizzlike or not. summon->GetMotionMaster()->MovePoint(0, triggerEndPos); } } diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp index bc8c7f877a9..3d21388ca11 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp @@ -809,7 +809,7 @@ class spell_blood_queen_pact_of_the_darkfallen_dmg : public SpellScriptLoader // this is an additional effect to be executed void PeriodicTick(AuraEffect const* aurEff) { - SpellInfo const* damageSpell = sSpellMgr->EnsureSpellInfo(SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE); + SpellInfo const* damageSpell = sSpellMgr->AssertSpellInfo(SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE); int32 damage = damageSpell->Effects[EFFECT_0].CalcValue(); float multiplier = 0.3375f + 0.1f * uint32(aurEff->GetTickNumber()/10); // do not convert to 0.01f - we need tick number/10 as INT (damage increases every 10 ticks) damage = int32(damage * multiplier); 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 9b0693ec95e..73a7de36580 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp @@ -1843,7 +1843,7 @@ class spell_igb_rocket_pack : public SpellScriptLoader void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { - SpellInfo const* damageInfo = sSpellMgr->EnsureSpellInfo(SPELL_ROCKET_PACK_DAMAGE); + SpellInfo const* damageInfo = sSpellMgr->AssertSpellInfo(SPELL_ROCKET_PACK_DAMAGE); GetTarget()->CastCustomSpell(SPELL_ROCKET_PACK_DAMAGE, SPELLVALUE_BASE_POINT0, 2 * (damageInfo->Effects[EFFECT_0].CalcValue() + aurEff->GetTickNumber() * aurEff->GetAmplitude()), NULL, TRIGGERED_FULL_MASK); GetTarget()->CastSpell(NULL, SPELL_ROCKET_BURST, TRIGGERED_FULL_MASK); } @@ -2461,6 +2461,33 @@ class spell_igb_teleport_players_on_victory : public SpellScriptLoader } }; +// 71201 - Battle Experience - proc should never happen, handled in script +class spell_igb_battle_experience_check : public SpellScriptLoader +{ +public: + spell_igb_battle_experience_check() : SpellScriptLoader("spell_igb_battle_experience_check") { } + + class spell_igb_battle_experience_check_AuraScript : public AuraScript + { + PrepareAuraScript(spell_igb_battle_experience_check_AuraScript); + + bool CheckProc(ProcEventInfo& /*eventInfo*/) + { + return false; + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_igb_battle_experience_check_AuraScript::CheckProc); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_igb_battle_experience_check_AuraScript(); + } +}; + class achievement_im_on_a_boat : public AchievementCriteriaScript { public: @@ -2500,5 +2527,6 @@ void AddSC_boss_icecrown_gunship_battle() new spell_igb_gunship_fall_teleport(); new spell_igb_check_for_players(); new spell_igb_teleport_players_on_victory(); + new spell_igb_battle_experience_check(); new achievement_im_on_a_boat(); } diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp index d3cf6495aa7..b3a11b8eb31 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp @@ -203,7 +203,7 @@ class DaranavanMoveEvent : public BasicEvent public: DaranavanMoveEvent(Creature& darnavan) : _darnavan(darnavan) { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _darnavan.GetMotionMaster()->MovePoint(POINT_DESPAWN, SummonPositions[6]); return true; @@ -421,7 +421,7 @@ class boss_lady_deathwhisper : public CreatureScript void UpdateAI(uint32 diff) override { - if ((!UpdateVictim() && !events.IsInPhase(PHASE_INTRO))) + if (!UpdateVictim() && !events.IsInPhase(PHASE_INTRO)) return; events.Update(diff); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp index 056231285e2..9f20799df82 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp @@ -142,7 +142,7 @@ class boss_lord_marrowgar : public CreatureScript void Reset() override { _Reset(); - me->SetSpeed(MOVE_RUN, _baseSpeed, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed); me->RemoveAurasDueToSpell(SPELL_BONE_STORM); me->RemoveAurasDueToSpell(SPELL_BERSERK); events.ScheduleEvent(EVENT_ENABLE_BONE_SLICE, 10000); @@ -224,7 +224,7 @@ class boss_lord_marrowgar : public CreatureScript case EVENT_BONE_STORM_BEGIN: if (Aura* pStorm = me->GetAura(SPELL_BONE_STORM)) pStorm->SetDuration(int32(_boneStormDuration)); - me->SetSpeed(MOVE_RUN, _baseSpeed*3.0f, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed*3.0f); Talk(SAY_BONE_STORM); events.ScheduleEvent(EVENT_BONE_STORM_END, _boneStormDuration+1); // no break here @@ -242,7 +242,7 @@ class boss_lord_marrowgar : public CreatureScript if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); me->GetMotionMaster()->MoveChase(me->GetVictim()); - me->SetSpeed(MOVE_RUN, _baseSpeed, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed); events.CancelEvent(EVENT_BONE_STORM_MOVE); events.ScheduleEvent(EVENT_ENABLE_BONE_SLICE, 10000); if (!IsHeroic()) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp index 2db9d206a00..fe6e4081326 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp @@ -369,21 +369,21 @@ class boss_professor_putricide : public CreatureScript { case POINT_FESTERGUT: instance->SetBossState(DATA_FESTERGUT, IN_PROGRESS); // needed here for delayed gate close - me->SetSpeed(MOVE_RUN, _baseSpeed, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed); DoAction(ACTION_FESTERGUT_GAS); if (Creature* festergut = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FESTERGUT))) festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, NULL, NULL, festergut->GetGUID()); break; case POINT_ROTFACE: instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close - me->SetSpeed(MOVE_RUN, _baseSpeed, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed); DoAction(ACTION_ROTFACE_OOZE); events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE); break; case POINT_TABLE: // stop attack me->GetMotionMaster()->MoveIdle(); - me->SetSpeed(MOVE_RUN, _baseSpeed, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed); if (GameObject* table = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_PUTRICIDE_TABLE))) me->SetFacingToObject(table); // operating on new phase already @@ -418,7 +418,7 @@ class boss_professor_putricide : public CreatureScript { case ACTION_FESTERGUT_COMBAT: SetPhase(PHASE_FESTERGUT); - me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); me->GetMotionMaster()->MovePoint(POINT_FESTERGUT, festergutWatchPos); me->SetReactState(REACT_PASSIVE); DoZoneInCombat(me); @@ -435,7 +435,7 @@ class boss_professor_putricide : public CreatureScript case ACTION_ROTFACE_COMBAT: { SetPhase(PHASE_ROTFACE); - me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); me->GetMotionMaster()->MovePoint(POINT_ROTFACE, rotfaceWatchPos); me->SetReactState(REACT_PASSIVE); _oozeFloodStage = 0; @@ -477,7 +477,7 @@ class boss_professor_putricide : public CreatureScript events.ScheduleEvent(EVENT_ROTFACE_DIES, 4500, 0, PHASE_ROTFACE); break; case ACTION_CHANGE_PHASE: - me->SetSpeed(MOVE_RUN, _baseSpeed*2.0f, true); + me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f); events.DelayEvents(30000); me->AttackStop(); if (!IsHeroic()) @@ -562,7 +562,7 @@ class boss_professor_putricide : public CreatureScript void UpdateAI(uint32 diff) override { - if ((!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) && !UpdateVictim())) + if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) && !UpdateVictim()) return; events.Update(diff); @@ -776,7 +776,7 @@ class npc_volatile_ooze : public CreatureScript { } - void CastMainSpell() + void CastMainSpell() override { me->CastSpell(me, SPELL_VOLATILE_OOZE_ADHESIVE, false); } @@ -800,7 +800,7 @@ class npc_gas_cloud : public CreatureScript _newTargetSelectTimer = 0; } - void CastMainSpell() + void CastMainSpell() override { me->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, me, false); } @@ -1257,7 +1257,7 @@ class spell_putricide_mutated_plague : public SpellScriptLoader return; uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; - SpellInfo const* spell = sSpellMgr->EnsureSpellInfo(triggerSpell); + SpellInfo const* spell = sSpellMgr->AssertSpellInfo(triggerSpell); spell = sSpellMgr->GetSpellForDifficultyFromSpell(spell, caster); int32 damage = spell->Effects[EFFECT_0].CalcValue(caster); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp index 683dd976b7a..bf69a49055c 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp @@ -856,14 +856,14 @@ class spell_rotface_vile_gas_trigger : public SpellScriptLoader GetCaster()->CastSpell(GetHitUnit(), SPELL_VILE_GAS_TRIGGER_SUMMON); } - void Register() + void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_rotface_vile_gas_trigger_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_rotface_vile_gas_trigger_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; - SpellScript* GetSpellScript() const + SpellScript* GetSpellScript() const override { return new spell_rotface_vile_gas_trigger_SpellScript(); } diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp index ac094588d35..aa5060e83b4 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp @@ -134,6 +134,7 @@ enum FrostwingData DATA_WHELP_MARKER = 2, DATA_LINKED_GAMEOBJECT = 3, DATA_TRAPPED_PLAYER = 4, + DATA_IS_THIRD_PHASE = 5 }; enum MovementPoints @@ -168,7 +169,7 @@ class FrostwyrmLandEvent : public BasicEvent public: FrostwyrmLandEvent(Creature& owner, Position const& dest) : _owner(owner), _dest(dest) { } - bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) + bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override { _owner.GetMotionMaster()->MoveLand(POINT_FROSTWYRM_LAND, _dest); return true; @@ -184,7 +185,7 @@ class FrostBombExplosion : public BasicEvent public: FrostBombExplosion(Creature* owner, ObjectGuid sindragosaGUID) : _owner(owner), _sindragosaGUID(sindragosaGUID) { } - bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) + bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override { _owner->CastSpell((Unit*)NULL, SPELL_FROST_BOMB, false, NULL, NULL, _sindragosaGUID); _owner->RemoveAurasDueToSpell(SPELL_FROST_BOMB_VISUAL); @@ -196,20 +197,19 @@ class FrostBombExplosion : public BasicEvent ObjectGuid _sindragosaGUID; }; -class FrostBeaconSelector +class FrostBeaconSelector : NonTankTargetSelector { public: - FrostBeaconSelector(Unit* source) : _source(source) { } + FrostBeaconSelector(Unit* source) : NonTankTargetSelector(source, true) { } - bool operator()(Unit* target) const + bool operator()(WorldObject* target) const { - return target->GetTypeId() == TYPEID_PLAYER && - target != _source->GetVictim() && - !target->HasAura(SPELL_ICE_TOMB_UNTARGETABLE); - } + if (Unit* unitTarget = target->ToUnit()) + return !NonTankTargetSelector::operator()(unitTarget) || + unitTarget->HasAura(SPELL_ICE_TOMB_UNTARGETABLE); - private: - Unit* _source; + return false; + } }; class boss_sindragosa : public CreatureScript @@ -315,7 +315,7 @@ class boss_sindragosa : public CreatureScript me->SetCanFly(true); me->SetDisableGravity(true); me->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND | UNIT_BYTE1_FLAG_HOVER); - me->SetSpeed(MOVE_FLIGHT, 4.0f); + me->SetSpeedRate(MOVE_FLIGHT, 4.0f); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); float moveTime = me->GetExactDist(&SindragosaFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f); me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, SindragosaLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250)); @@ -326,9 +326,15 @@ class boss_sindragosa : public CreatureScript uint32 GetData(uint32 type) const override { - if (type == DATA_MYSTIC_BUFFET_STACK) - return _mysticBuffetStack; - return 0xFFFFFFFF; + switch (type) + { + case DATA_MYSTIC_BUFFET_STACK: + return _mysticBuffetStack; + case DATA_IS_THIRD_PHASE: + return _isThirdPhase; + default: + return 0xFFFFFFFF; + } } void MovementInform(uint32 type, uint32 point) override @@ -345,7 +351,7 @@ class boss_sindragosa : public CreatureScript me->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND | UNIT_BYTE1_FLAG_HOVER); me->SetHomePosition(SindragosaLandPos); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - me->SetSpeed(MOVE_FLIGHT, 2.5f); + me->SetSpeedRate(MOVE_FLIGHT, 2.5f); // Sindragosa enters combat as soon as she lands DoZoneInCombat(); @@ -419,7 +425,6 @@ class boss_sindragosa : public CreatureScript if (spellId == spell->Id) if (Aura const* mysticBuffet = target->GetAura(spell->Id)) _mysticBuffetStack = std::max<uint8>(_mysticBuffetStack, mysticBuffet->GetStackAmount()); - } void UpdateAI(uint32 diff) override @@ -494,11 +499,7 @@ class boss_sindragosa : public CreatureScript me->GetMotionMaster()->MovePoint(POINT_AIR_PHASE_FAR, SindragosaAirPosFar); break; case EVENT_ICE_TOMB: - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, FrostBeaconSelector(me))) - { - Talk(EMOTE_WARN_FROZEN_ORB, target); - me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, 1, nullptr, TRIGGERED_FULL_MASK); - } + me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, 1, nullptr, TRIGGERED_FULL_MASK); events.ScheduleEvent(EVENT_ICE_TOMB, urand(16000, 23000)); break; case EVENT_FROST_BOMB: @@ -603,6 +604,7 @@ class npc_ice_tomb : public CreatureScript _trappedPlayerGUID.Clear(); player->RemoveAurasDueToSpell(SPELL_ICE_TOMB_DAMAGE); player->RemoveAurasDueToSpell(SPELL_ASPHYXIATION); + player->RemoveAurasDueToSpell(SPELL_ICE_TOMB_UNTARGETABLE); } } @@ -696,7 +698,7 @@ class npc_spinestalker : public CreatureScript return; me->setActive(true); - me->SetSpeed(MOVE_FLIGHT, 2.0f); + me->SetSpeedRate(MOVE_FLIGHT, 2.0f); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); float moveTime = me->GetExactDist(&SpinestalkerFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f); me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, SpinestalkerLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250)); @@ -833,7 +835,7 @@ class npc_rimefang : public CreatureScript return; me->setActive(true); - me->SetSpeed(MOVE_FLIGHT, 2.0f); + me->SetSpeedRate(MOVE_FLIGHT, 2.0f); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); float moveTime = me->GetExactDist(&RimefangFlyPos) / (me->GetSpeed(MOVE_FLIGHT) * 0.001f); me->m_Events.AddEvent(new FrostwyrmLandEvent(*me, RimefangLandPos), me->m_Events.CalculateTime(uint64(moveTime) + 250)); @@ -1283,9 +1285,9 @@ class spell_sindragosa_ice_tomb : public SpellScriptLoader public: spell_sindragosa_ice_tomb() : SpellScriptLoader("spell_sindragosa_ice_tomb_trap") { } - class spell_sindragosa_ice_tomb_SpellScript : public SpellScript + class spell_sindragosa_ice_tomb_AuraScript : public AuraScript { - PrepareSpellScript(spell_sindragosa_ice_tomb_SpellScript); + PrepareAuraScript(spell_sindragosa_ice_tomb_AuraScript); bool Validate(SpellInfo const* /*spell*/) override { @@ -1296,46 +1298,42 @@ class spell_sindragosa_ice_tomb : public SpellScriptLoader return true; } - void SummonTomb() + void PeriodicTick(AuraEffect const* aurEff) { - Position pos = GetHitUnit()->GetPosition(); - if (TempSummon* summon = GetCaster()->SummonCreature(NPC_ICE_TOMB, pos)) + PreventDefaultAction(); + + if (aurEff->GetTickNumber() == 1) { - summon->AI()->SetGUID(GetHitUnit()->GetGUID(), DATA_TRAPPED_PLAYER); - if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0)) + if (Unit* caster = GetCaster()) { - go->SetSpellId(SPELL_ICE_TOMB_DAMAGE); - summon->AddGameObject(go); + Position pos = GetTarget()->GetPosition(); + + if (TempSummon* summon = caster->SummonCreature(NPC_ICE_TOMB, pos)) + { + summon->AI()->SetGUID(GetTarget()->GetGUID(), DATA_TRAPPED_PLAYER); + GetTarget()->CastSpell(GetTarget(), SPELL_ICE_TOMB_UNTARGETABLE); + if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos, G3D::Quat(), 0)) + { + go->SetSpellId(SPELL_ICE_TOMB_DAMAGE); + summon->AddGameObject(go); + } + } } } } - void Register() override + void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { - AfterHit += SpellHitFn(spell_sindragosa_ice_tomb_SpellScript::SummonTomb); - } - }; - - class spell_sindragosa_ice_tomb_AuraScript : public AuraScript - { - PrepareAuraScript(spell_sindragosa_ice_tomb_AuraScript); - - void PeriodicTick(AuraEffect const* /*aurEff*/) - { - PreventDefaultAction(); + GetTarget()->RemoveAurasDueToSpell(SPELL_ICE_TOMB_UNTARGETABLE); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_sindragosa_ice_tomb_AuraScript::PeriodicTick, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + AfterEffectRemove += AuraEffectRemoveFn(spell_sindragosa_ice_tomb_AuraScript::HandleRemove, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } }; - SpellScript* GetSpellScript() const override - { - return new spell_sindragosa_ice_tomb_SpellScript(); - } - AuraScript* GetAuraScript() const override { return new spell_sindragosa_ice_tomb_AuraScript(); @@ -1576,6 +1574,41 @@ class spell_frostwarden_handler_focus_fire : public SpellScriptLoader } }; +class spell_sindragosa_ice_tomb_target : public SpellScriptLoader +{ +public: + spell_sindragosa_ice_tomb_target() : SpellScriptLoader("spell_sindragosa_ice_tomb_target") { } + + class spell_sindragosa_ice_tomb_target_SpellScript : public SpellScript + { + PrepareSpellScript(spell_sindragosa_ice_tomb_target_SpellScript); + + void FilterTargets(std::list<WorldObject*>& unitList) + { + Unit* caster = GetCaster(); + unitList.remove_if(FrostBeaconSelector(caster)); + } + + void HandleSindragosaTalk(SpellEffIndex /*effIndex*/) + { + if (Creature* creatureCaster = GetCaster()->ToCreature()) + if (creatureCaster->GetAI()->GetData(DATA_IS_THIRD_PHASE)) + creatureCaster->AI()->Talk(EMOTE_WARN_FROZEN_ORB, GetHitUnit()); + } + + void Register() override + { + OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_sindragosa_ice_tomb_target_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); + OnEffectLaunchTarget += SpellEffectFn(spell_sindragosa_ice_tomb_target_SpellScript::HandleSindragosaTalk, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_sindragosa_ice_tomb_target_SpellScript(); + } +}; + class at_sindragosa_lair : public AreaTriggerScript { public: @@ -1641,6 +1674,7 @@ void AddSC_boss_sindragosa() new spell_frostwarden_handler_focus_fire(); new spell_trigger_spell_from_caster("spell_sindragosa_ice_tomb", SPELL_ICE_TOMB_DUMMY, TRIGGERED_IGNORE_SET_FACING); new spell_trigger_spell_from_caster("spell_sindragosa_ice_tomb_dummy", SPELL_FROST_BEACON); + new spell_sindragosa_ice_tomb_target(); new at_sindragosa_lair(); new achievement_all_you_can_eat(); } 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 a598b09c71b..de8d65693b9 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp @@ -285,6 +285,7 @@ enum Phases #define PHASE_TWO_THREE (events.IsInPhase(PHASE_TWO) ? PHASE_TWO : PHASE_THREE) Position const CenterPosition = {503.6282f, -2124.655f, 840.8569f, 0.0f}; +Position const TirionSpawn = {505.2118f, -2124.353f, 840.9403f, 3.141593f}; Position const TirionIntro = {489.2970f, -2124.840f, 840.8569f, 0.0f}; Position const TirionCharge = {482.9019f, -2124.479f, 840.8570f, 0.0f}; Position const LichKingIntro[3] = @@ -436,7 +437,7 @@ class StartMovementEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _owner->SetReactState(REACT_AGGRESSIVE); if (Creature* _summoner = ObjectAccessor::GetCreature(*_owner, _summonerGuid)) @@ -458,7 +459,7 @@ class VileSpiritActivateEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _owner->SetReactState(REACT_AGGRESSIVE); _owner->CastSpell(_owner, SPELL_VILE_SPIRIT_MOVE_SEARCH, true); @@ -478,7 +479,7 @@ class TriggerWickedSpirit : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _owner->CastCustomSpell(SPELL_TRIGGER_VILE_SPIRIT_HEROIC, SPELLVALUE_MAX_TARGETS, 1, NULL, true); @@ -514,13 +515,34 @@ class boss_the_lich_king : public CreatureScript _vileSpiritExplosions = 0; } - void Reset() override + void InitializeAI() override + { + SetupEncounter(); + } + + void JustRespawned() override + { + SetupEncounter(); + } + + void SetupEncounter() { _Reset(); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); me->SetReactState(REACT_PASSIVE); events.SetPhase(PHASE_INTRO); Initialize(); SetEquipmentSlots(true); + + // Reset The Frozen Throne gameobjects + FrozenThroneResetWorker reset; + Trinity::GameObjectWorker<FrozenThroneResetWorker> worker(me, reset); + me->VisitNearbyGridObject(333.0f, worker); + + // Reset any light override + me->GetMap()->SetZoneOverrideLight(AREA_THE_FROZEN_THRONE, 0, 5000); + + me->SummonCreature(NPC_HIGHLORD_TIRION_FORDRING_LK, TirionSpawn, TEMPSUMMON_MANUAL_DESPAWN); } void JustDied(Unit* /*killer*/) override @@ -556,40 +578,21 @@ class boss_the_lich_king : public CreatureScript events.ScheduleEvent(EVENT_SHADOW_TRAP, 15500, 0, PHASE_ONE); } - void JustReachedHome() override - { - _JustReachedHome(); - instance->SetBossState(DATA_THE_LICH_KING, NOT_STARTED); - - // Reset The Frozen Throne gameobjects - FrozenThroneResetWorker reset; - Trinity::GameObjectWorker<FrozenThroneResetWorker> worker(me, reset); - me->VisitNearbyGridObject(333.0f, worker); - - // Restore Tirion's gossip only after The Lich King fully resets to prevent - // restarting the encounter while LK still runs back to spawn point - if (Creature* tirion = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HIGHLORD_TIRION_FORDRING))) - tirion->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - - // Reset any light override - me->GetMap()->SetZoneOverrideLight(AREA_THE_FROZEN_THRONE, 0, 5000); - } - bool CanAIAttack(Unit const* target) const override { // The Lich King must not select targets in frostmourne room if he killed everyone outside return !target->HasAura(SPELL_IN_FROSTMOURNE_ROOM) && BossAI::CanAIAttack(target); } - void EnterEvadeMode(EvadeReason why) override + void EnterEvadeMode(EvadeReason /*why*/) override { - instance->SetBossState(DATA_THE_LICH_KING, FAIL); - BossAI::EnterEvadeMode(why); if (Creature* tirion = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HIGHLORD_TIRION_FORDRING))) - tirion->AI()->EnterEvadeMode(); + tirion->DespawnOrUnsummon(); DoCastAOE(SPELL_KILL_FROSTMOURNE_PLAYERS); EntryCheckPredicate pred(NPC_STRANGULATE_VEHICLE); summons.DoAction(ACTION_TELEPORT_BACK, pred); + summons.DespawnAll(); + _DespawnAtEvade(); } void KilledUnit(Unit* victim) override @@ -761,7 +764,7 @@ class boss_the_lich_king : public CreatureScript { summons.Summon(summon); summon->SetReactState(REACT_PASSIVE); - summon->SetSpeed(MOVE_FLIGHT, 0.5f); + summon->SetSpeedRate(MOVE_FLIGHT, 0.5f); summon->GetMotionMaster()->MoveRandom(10.0f); if (!events.IsInPhase(PHASE_FROSTMOURNE)) summon->m_Events.AddEvent(new VileSpiritActivateEvent(summon), summon->m_Events.CalculateTime(15000)); @@ -770,6 +773,8 @@ class boss_the_lich_king : public CreatureScript case NPC_STRANGULATE_VEHICLE: summons.Summon(summon); return; + case NPC_HIGHLORD_TIRION_FORDRING_LK: + return; default: break; } @@ -1153,6 +1158,7 @@ class npc_tirion_fordring_tft : public CreatureScript _events.Reset(); if (_instance->GetBossState(DATA_THE_LICH_KING) == DONE) me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); + me->LoadEquipment(1); } void MovementInform(uint32 type, uint32 id) override @@ -1443,7 +1449,7 @@ class npc_valkyr_shadowguard : public CreatureScript _events.Reset(); me->SetReactState(REACT_PASSIVE); DoCast(me, SPELL_WINGS_OF_THE_DAMNED, false); - me->SetSpeed(MOVE_FLIGHT, 0.642857f, true); + me->SetSpeedRate(MOVE_FLIGHT, 0.642857f); } void IsSummonedBy(Unit* /*summoner*/) override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp index 4f35f848927..b07de3457bd 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp @@ -179,7 +179,7 @@ class DelayedCastEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _trigger->CastSpell(_trigger, _spellId, false, NULL, NULL, _originalCaster); if (_despawnTime) @@ -201,7 +201,7 @@ class AuraRemoveEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _trigger->RemoveAurasDueToSpell(_spellId); return true; @@ -219,7 +219,7 @@ class ValithriaDespawner : public BasicEvent { } - bool Execute(uint64 /*currTime*/, uint32 /*diff*/) + bool Execute(uint64 /*currTime*/, uint32 /*diff*/) override { Trinity::CreatureWorker<ValithriaDespawner> worker(_creature, *this); _creature->VisitNearbyGridObject(333.0f, worker); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp index 25ca99f6a20..abb9c025771 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp @@ -365,7 +365,7 @@ class CaptainSurviveTalk : public BasicEvent public: explicit CaptainSurviveTalk(Creature const& owner) : _owner(owner) { } - bool Execute(uint64 /*currTime*/, uint32 /*diff*/) + bool Execute(uint64 /*currTime*/, uint32 /*diff*/) override { _owner.AI()->Talk(SAY_CAPTAIN_SURVIVE_TALK); return true; diff --git a/src/server/scripts/Northrend/IsleOfConquest/boss_ioc_horde_alliance.cpp b/src/server/scripts/Northrend/IsleOfConquest/boss_ioc_horde_alliance.cpp new file mode 100644 index 00000000000..71d90da21a1 --- /dev/null +++ b/src/server/scripts/Northrend/IsleOfConquest/boss_ioc_horde_alliance.cpp @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "BattlegroundIC.h" + +enum BossSpells +{ + SPELL_BRUTAL_STRIKE = 58460, + SPELL_DAGGER_THROW = 67280, + SPELL_CRUSHING_LEAP = 68506, + SPELL_RAGE = 66776 +}; + +enum BossEvents +{ + EVENT_BRUTAL_STRIKE = 1, + EVENT_DAGGER_THROW = 2, + EVENT_CRUSHING_LEAP = 3, + EVENT_CHECK_RANGE = 4 +}; + +class boss_ioc_horde_alliance : public CreatureScript +{ +public: + boss_ioc_horde_alliance() : CreatureScript("boss_ioc_horde_alliance") { } + + struct boss_ioc_horde_allianceAI : public ScriptedAI + { + boss_ioc_horde_allianceAI(Creature* creature) : ScriptedAI(creature) { } + + void Reset() override + { + _events.Reset(); + + uint32 _npcGuard; + if (me->GetEntry() == NPC_HIGH_COMMANDER_HALFORD_WYRMBANE) + _npcGuard = NPC_SEVEN_TH_LEGION_INFANTRY; + else + _npcGuard = NPC_KOR_KRON_GUARD; + + std::list<Creature*> guardsList; + me->GetCreatureListWithEntryInGrid(guardsList, _npcGuard, 100.0f); + for (std::list<Creature*>::const_iterator itr = guardsList.begin(); itr != guardsList.end(); ++itr) + (*itr)->Respawn(); + }; + + void EnterCombat(Unit* /*who*/) override + { + _events.ScheduleEvent(EVENT_BRUTAL_STRIKE, 5 * IN_MILLISECONDS); + _events.ScheduleEvent(EVENT_DAGGER_THROW, 7 * IN_MILLISECONDS); + _events.ScheduleEvent(EVENT_CHECK_RANGE, 1 * IN_MILLISECONDS); + _events.ScheduleEvent(EVENT_CRUSHING_LEAP, 15 * IN_MILLISECONDS); + } + + void SpellHit(Unit* caster, SpellInfo const* /*spell*/) override + { + if (caster->IsVehicle()) + me->Kill(caster); + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + _events.Update(diff); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_BRUTAL_STRIKE: + DoCastVictim(SPELL_BRUTAL_STRIKE); + _events.ScheduleEvent(EVENT_BRUTAL_STRIKE, 5 * IN_MILLISECONDS); + break; + case EVENT_DAGGER_THROW: + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1)) + DoCast(target, SPELL_DAGGER_THROW); + _events.ScheduleEvent(EVENT_DAGGER_THROW, 7 * IN_MILLISECONDS); + break; + case EVENT_CRUSHING_LEAP: + DoCastVictim(SPELL_CRUSHING_LEAP); + _events.ScheduleEvent(EVENT_CRUSHING_LEAP, 25 * IN_MILLISECONDS); + break; + case EVENT_CHECK_RANGE: + if (me->GetDistance(me->GetHomePosition()) > 25.0f) + DoCast(me, SPELL_RAGE); + else + me->RemoveAurasDueToSpell(SPELL_RAGE); + _events.ScheduleEvent(EVENT_CHECK_RANGE, 1 * IN_MILLISECONDS); + break; + default: + break; + } + } + + DoMeleeAttackIfReady(); + } + + private: + EventMap _events; + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_ioc_horde_allianceAI(creature); + } +}; + +void AddSC_boss_ioc_horde_alliance() +{ + new boss_ioc_horde_alliance(); +} diff --git a/src/server/scripts/Northrend/isle_of_conquest.cpp b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp index 68121e940c9..f7e83ff1f42 100644 --- a/src/server/scripts/Northrend/isle_of_conquest.cpp +++ b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp @@ -210,7 +210,7 @@ class StartLaunchEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { Player* player = sObjectMgr->GetPlayerByLowGUID(_lowGuid); if (!player || !player->GetVehicle()) @@ -259,6 +259,58 @@ class spell_ioc_launch : public SpellScriptLoader } }; +enum SeaforiumBombSpells +{ + SPELL_SEAFORIUM_BLAST = 66676, + SPELL_HUGE_SEAFORIUM_BLAST = 66672, + SPELL_A_BOMB_INABLE_CREDIT = 68366, + SPELL_A_BOMB_INATION_CREDIT = 68367 +}; + +class spell_ioc_seaforium_blast_credit : public SpellScriptLoader +{ + public: + spell_ioc_seaforium_blast_credit() : SpellScriptLoader("spell_ioc_seaforium_blast_credit") { } + + class spell_ioc_seaforium_blast_credit_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ioc_seaforium_blast_credit_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_A_BOMB_INABLE_CREDIT) || !sSpellMgr->GetSpellInfo(SPELL_A_BOMB_INATION_CREDIT)) + return false; + return true; + } + + void HandleAchievementCredit(SpellEffIndex /*effIndex*/) + { + uint32 _creditSpell = 0; + Unit* caster = GetOriginalCaster(); + if (!caster) + return; + + if (GetSpellInfo()->Id == SPELL_SEAFORIUM_BLAST) + _creditSpell = SPELL_A_BOMB_INABLE_CREDIT; + else if (GetSpellInfo()->Id == SPELL_HUGE_SEAFORIUM_BLAST) + _creditSpell = SPELL_A_BOMB_INATION_CREDIT; + + if (GetHitGObj() && GetHitGObj()->IsDestructibleBuilding()) + caster->CastSpell(caster, _creditSpell, true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_ioc_seaforium_blast_credit_SpellScript::HandleAchievementCredit, EFFECT_1, SPELL_EFFECT_GAMEOBJECT_DAMAGE); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_ioc_seaforium_blast_credit_SpellScript(); + } +}; + void AddSC_isle_of_conquest() { new npc_four_car_garage(); @@ -266,4 +318,5 @@ void AddSC_isle_of_conquest() new spell_ioc_gunship_portal(); new spell_ioc_parachute_ic(); new spell_ioc_launch(); + new spell_ioc_seaforium_blast_credit(); } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp index e8c4216b00e..60c60640c04 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp @@ -162,13 +162,13 @@ public: summons.DoZoneInCombat(); events.SetPhase(PHASE_NORMAL); - events.ScheduleEvent(EVENT_IMPALE, urand(10 * IN_MILLISECONDS, 20 * IN_MILLISECONDS), 0, PHASE_NORMAL); - events.ScheduleEvent(EVENT_SCARABS, urand(20 * IN_MILLISECONDS, 30 * IN_MILLISECONDS), 0, PHASE_NORMAL); - events.ScheduleEvent(EVENT_LOCUST, urand(80,120) * IN_MILLISECONDS, 0, PHASE_NORMAL); - events.ScheduleEvent(EVENT_BERSERK, 10 * MINUTE * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_IMPALE, randtime(Seconds(10), Seconds(20)), 0, PHASE_NORMAL); + events.ScheduleEvent(EVENT_SCARABS, randtime(Seconds(20), Seconds(30)), 0, PHASE_NORMAL); + events.ScheduleEvent(EVENT_LOCUST, Minutes(1)+randtime(Seconds(40), Seconds(60)), 0, PHASE_NORMAL); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); if (!Is25ManRaid()) - events.ScheduleEvent(EVENT_SPAWN_GUARD, urand(15, 20) * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_SPAWN_GUARD, randtime(Seconds(15), Seconds(20))); } void UpdateAI(uint32 diff) override @@ -189,11 +189,9 @@ public: else EnterEvadeMode(); - events.ScheduleEvent(EVENT_IMPALE, urand(10 * IN_MILLISECONDS, 20 * IN_MILLISECONDS), 0, PHASE_NORMAL); + events.Repeat(randtime(Seconds(10), Seconds(20))); break; case EVENT_SCARABS: - events.ScheduleEvent(EVENT_SCARABS, urand(40 * IN_MILLISECONDS, 60 * IN_MILLISECONDS), 0, PHASE_NORMAL); - if (!guardCorpses.empty()) { if (ObjectGuid target = Trinity::Containers::SelectRandomContainerElement(guardCorpses)) @@ -204,27 +202,28 @@ public: creatureTarget->DespawnOrUnsummon(); } } + events.Repeat(randtime(Seconds(40), Seconds(60))); break; case EVENT_LOCUST: Talk(EMOTE_LOCUST); + events.SetPhase(PHASE_SWARM); DoCast(me, SPELL_LOCUST_SWARM); - events.ScheduleEvent(EVENT_SPAWN_GUARD, 3 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_LOCUST_ENDS, RAID_MODE(19, 23) * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_LOCUST, 90000); - events.SetPhase(PHASE_SWARM); + events.ScheduleEvent(EVENT_SPAWN_GUARD, Seconds(3)); + events.ScheduleEvent(EVENT_LOCUST_ENDS, RAID_MODE(Seconds(19), Seconds(23))); + events.Repeat(Minutes(1)+Seconds(30)); break; case EVENT_LOCUST_ENDS: - events.ScheduleEvent(EVENT_IMPALE, urand(10 * IN_MILLISECONDS, 20 * IN_MILLISECONDS), 0, PHASE_NORMAL); - events.ScheduleEvent(EVENT_SCARABS, urand(20 * IN_MILLISECONDS, 30 * IN_MILLISECONDS), 0, PHASE_NORMAL); events.SetPhase(PHASE_NORMAL); + events.ScheduleEvent(EVENT_IMPALE, randtime(Seconds(10), Seconds(20)), 0, PHASE_NORMAL); + events.ScheduleEvent(EVENT_SCARABS, randtime(Seconds(20), Seconds(30)), 0, PHASE_NORMAL); break; case EVENT_SPAWN_GUARD: me->SummonCreatureGroup(GROUP_SINGLE_SPAWN); break; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); - events.ScheduleEvent(EVENT_BERSERK, 600000); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); break; } } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp index 39c41c935bf..8a7bdd293ba 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp @@ -100,9 +100,9 @@ class boss_faerlina : public CreatureScript _EnterCombat(); Talk(SAY_AGGRO); summons.DoZoneInCombat(); - events.ScheduleEvent(EVENT_POISON, urand(10 * IN_MILLISECONDS, 15 * IN_MILLISECONDS)); - events.ScheduleEvent(EVENT_FIRE, urand(6 * IN_MILLISECONDS, 18 * IN_MILLISECONDS)); - events.ScheduleEvent(EVENT_FRENZY, urand(60 * IN_MILLISECONDS, 80 * IN_MILLISECONDS)); + events.ScheduleEvent(EVENT_POISON, randtime(Seconds(10), Seconds(15))); + events.ScheduleEvent(EVENT_FIRE, randtime(Seconds(6), Seconds(18))); + events.ScheduleEvent(EVENT_FRENZY, Minutes(1)+randtime(Seconds(0), Seconds(20))); } void Reset() override @@ -111,9 +111,9 @@ class boss_faerlina : public CreatureScript _frenzyDispels = 0; } - void KilledUnit(Unit* /*victim*/) override + void KilledUnit(Unit* victim) override { - if (!urand(0, 2)) + if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } @@ -158,21 +158,21 @@ class boss_faerlina : public CreatureScript case EVENT_POISON: if (!me->HasAura(SPELL_WIDOWS_EMBRACE_HELPER)) DoCastAOE(SPELL_POISON_BOLT_VOLLEY); - events.ScheduleEvent(EVENT_POISON, urand(8000, 15000)); + events.Repeat(randtime(Seconds(8), Seconds(15))); break; case EVENT_FIRE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_RAIN_OF_FIRE); - events.ScheduleEvent(EVENT_FIRE, urand(6000, 18000)); + events.Repeat(randtime(Seconds(6), Seconds(18))); break; case EVENT_FRENZY: if (Aura* widowsEmbrace = me->GetAura(SPELL_WIDOWS_EMBRACE_HELPER)) - events.ScheduleEvent(EVENT_FRENZY, widowsEmbrace->GetDuration()+1 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_FRENZY, Milliseconds(widowsEmbrace->GetDuration()+1)); else { DoCast(SPELL_FRENZY); Talk(EMOTE_FRENZY); - events.ScheduleEvent(EVENT_FRENZY, urand(60 * IN_MILLISECONDS, 80 * IN_MILLISECONDS)); + events.Repeat(Minutes(1) + randtime(Seconds(0), Seconds(20))); } break; } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp index a7a89f44d81..0de1c4785b8 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp @@ -285,7 +285,7 @@ struct boss_four_horsemen_baseAI : public BossAI void EnterCombat(Unit* /*who*/) override { - if (instance->GetBossState(BOSS_HORSEMEN) != NOT_STARTED) // another horseman already did it + if (instance->GetBossState(BOSS_HORSEMEN) == IN_PROGRESS || instance->GetBossState(BOSS_HORSEMEN) == DONE) // another horseman already did it return; Talk(SAY_AGGRO); BeginEncounter(); @@ -411,9 +411,9 @@ class boss_four_horsemen_baron : public CreatureScript else AttackStart(threat.getHostilTarget()); - events.ScheduleEvent(EVENT_BERSERK, 10 * MINUTE * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_MARK, 24 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_UNHOLYSHADOW, urandms(3,7)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); + events.ScheduleEvent(EVENT_MARK, Seconds(24)); + events.ScheduleEvent(EVENT_UNHOLYSHADOW, randtime(Seconds(3), Seconds(7))); } void _UpdateAI(uint32 diff) override @@ -431,11 +431,11 @@ class boss_four_horsemen_baron : public CreatureScript break; case EVENT_MARK: DoCastAOE(SPELL_BARON_MARK, true); - events.ScheduleEvent(EVENT_MARK, 12 * IN_MILLISECONDS); + events.Repeat(Seconds(12)); break; case EVENT_UNHOLYSHADOW: DoCastVictim(SPELL_UNHOLY_SHADOW); - events.ScheduleEvent(EVENT_UNHOLYSHADOW, urandms(10,30)); + events.Repeat(randtime(Seconds(10), Seconds(30))); break; } } @@ -484,9 +484,9 @@ class boss_four_horsemen_thane : public CreatureScript else AttackStart(threat.getHostilTarget()); - events.ScheduleEvent(EVENT_BERSERK, 10 * MINUTE * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_MARK, 24 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_METEOR, urandms(10,15)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); + events.ScheduleEvent(EVENT_MARK, Seconds(24)); + events.ScheduleEvent(EVENT_METEOR, randtime(Seconds(10), Seconds(25))); } void _UpdateAI(uint32 diff) override { @@ -503,7 +503,7 @@ class boss_four_horsemen_thane : public CreatureScript break; case EVENT_MARK: DoCastAOE(SPELL_THANE_MARK, true); - events.ScheduleEvent(EVENT_MARK, 12 * IN_MILLISECONDS); + events.Repeat(Seconds(12)); break; case EVENT_METEOR: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 20.0f, true)) @@ -511,7 +511,7 @@ class boss_four_horsemen_thane : public CreatureScript DoCast(target, SPELL_METEOR); _shouldSay = true; } - events.ScheduleEvent(EVENT_METEOR, urandms(13,17)); + events.Repeat(randtime(Seconds(13), Seconds(17))); break; } } @@ -550,9 +550,9 @@ class boss_four_horsemen_lady : public CreatureScript boss_four_horsemen_ladyAI(Creature* creature) : boss_four_horsemen_baseAI(creature, LADY, ladyPath) { } void BeginFighting() override { - events.ScheduleEvent(EVENT_BERSERK, 10 * MINUTE * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_MARK, 24 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_VOIDZONE, urandms(5,10)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); + events.ScheduleEvent(EVENT_MARK, Seconds(24)); + events.ScheduleEvent(EVENT_VOIDZONE, randtime(Seconds(5), Seconds(10))); } void _UpdateAI(uint32 diff) override @@ -578,7 +578,7 @@ class boss_four_horsemen_lady : public CreatureScript break; case EVENT_MARK: DoCastAOE(SPELL_LADY_MARK, true); - events.ScheduleEvent(EVENT_MARK, 15 * IN_MILLISECONDS); + events.Repeat(Seconds(15)); break; case EVENT_VOIDZONE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true)) @@ -586,7 +586,7 @@ class boss_four_horsemen_lady : public CreatureScript DoCast(target, SPELL_VOID_ZONE, true); Talk(SAY_SPECIAL); } - events.ScheduleEvent(EVENT_VOIDZONE, urandms(12, 18)); + events.Repeat(randtime(Seconds(12), Seconds(18))); break; } } @@ -620,9 +620,9 @@ class boss_four_horsemen_sir : public CreatureScript boss_four_horsemen_sirAI(Creature* creature) : boss_four_horsemen_baseAI(creature, SIR, sirPath), _shouldSay(true) { } void BeginFighting() override { - events.ScheduleEvent(EVENT_BERSERK, 10 * MINUTE * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_MARK, 24 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_HOLYWRATH, urandms(13,18)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(10)); + events.ScheduleEvent(EVENT_MARK, Seconds(24)); + events.ScheduleEvent(EVENT_HOLYWRATH, randtime(Seconds(13), Seconds(18))); } void _UpdateAI(uint32 diff) override @@ -648,7 +648,7 @@ class boss_four_horsemen_sir : public CreatureScript break; case EVENT_MARK: DoCastAOE(SPELL_SIR_MARK, true); - events.ScheduleEvent(EVENT_MARK, 15 * IN_MILLISECONDS); + events.Repeat(Seconds(15)); break; case EVENT_HOLYWRATH: if (Unit* target = SelectTarget(SELECT_TARGET_NEAREST, 0, 45.0f, true)) @@ -656,7 +656,7 @@ class boss_four_horsemen_sir : public CreatureScript DoCast(target, SPELL_HOLY_WRATH, true); _shouldSay = true; } - events.ScheduleEvent(EVENT_HOLYWRATH, urandms(10,18)); + events.Repeat(randtime(Seconds(10), Seconds(18))); break; } } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp index ec47b0db101..6ec9af68723 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp @@ -18,38 +18,74 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "naxxramas.h" +#include "SpellScript.h" +#include <math.h> -enum Spells +enum Texts { - SPELL_MORTAL_WOUND = 25646, - SPELL_ENRAGE = 28371, - SPELL_DECIMATE = 28374, - SPELL_BERSERK = 26662, - SPELL_INFECTED_WOUND = 29306 + EMOTE_SPOTS_ONE = 0, + EMOTE_DECIMATE = 1, + EMOTE_ENRAGE = 2, + EMOTE_DEVOURS_ALL = 3, + EMOTE_BERSERKER = 4 }; -enum Creatures +enum Spells { - NPC_ZOMBIE = 16360 + // Gluth + SPELL_MORTAL_WOUND = 54378, // spell effect dummy unused. what its supposed to do is unkown. + SPELL_ENRAGE = 28371, // 54427 in 25 man. + SPELL_DECIMATE = 28374, // 54426 in 25 man. Effect0 is handled by SpellScript (see below) and 2 rows in conditions table. Effect2 is handled by SpellScript (see below). + SPELL_DECIMATE_DMG = 28375, + SPELL_BERSERK = 26662, + SPELL_ZOMBIE_CHOW_SEARCH_SINGLE = 28239, // Insta kill spell. Single target. See spell script below. + SPELL_ZOMBIE_CHOW_SEARCH_MULTI = 28404, // Insta kill spell. Affect all zombies 10 yards around Gluth's center. See one row conditions table + spell script below. + + // Zombies + SPELL_INFECTED_WOUND = 29307 // Used by the zombies on self. }; Position const PosSummon[3] = { - {3267.9f, -3172.1f, 297.42f, 0.94f}, - {3253.2f, -3132.3f, 297.42f, 0}, - {3308.3f, -3185.8f, 297.42f, 1.58f}, + { 3270.132f, -3169.948f, 297.5891f, 5.88176f }, + { 3307.298f, -3183.449f, 297.5891f, 5.742133f }, + { 3255.708f, -3135.677f, 297.5891f, 1.867502f } }; enum Events { - EVENT_WOUND = 1, + EVENT_WOUND = 1, EVENT_ENRAGE, EVENT_DECIMATE, EVENT_BERSERK, EVENT_SUMMON, + EVENT_SEARCH_ZOMBIE_SINGLE, + EVENT_KILL_ZOMBIE_SINGLE, + EVENT_SEARCH_ZOMBIE_MULTI }; -#define EMOTE_NEARBY " spots a nearby zombie to devour!" +enum States +{ + STATE_GLUTH_NORMAL = 1, + STATE_GLUTH_EATING = 2, + + STATE_ZOMBIE_NORMAL = 1, + STATE_ZOMBIE_DECIMATED = 2, + STATE_ZOMBIE_TOBE_EATEN = 3 +}; + +enum SummonGroups +{ + SUMMON_GROUP_CHOW_10MAN = 1, + SUMMON_GROUP_CHOW_25MAN = 2 +}; + +enum Misc +{ + EVENT_GLUTH_ZOMBIE_BEHAVIOR = 10495, // unused. event handled by spell_gluth_decimate_SpellScript::HandleEvent + DATA_ZOMBIE_STATE = 1, + ACTION_DECIMATE_EVENT = 2, +}; class boss_gluth : public CreatureScript { @@ -58,99 +94,390 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_gluthAI(creature); + return GetInstanceAI<boss_gluthAI>(creature); } struct boss_gluthAI : public BossAI { - boss_gluthAI(Creature* creature) : BossAI(creature, BOSS_GLUTH) - { - // Do not let Gluth be affected by zombies' debuff - me->ApplySpellImmune(0, IMMUNITY_ID, SPELL_INFECTED_WOUND, true); - } - void MoveInLineOfSight(Unit* who) override + boss_gluthAI(Creature* creature) : BossAI(creature, BOSS_GLUTH), state(STATE_GLUTH_NORMAL) {} + + void Reset() override { - if (who->GetEntry() == NPC_ZOMBIE && me->IsWithinDistInMap(who, 7)) - { - SetGazeOn(who); - /// @todo use a script text - me->TextEmote(EMOTE_NEARBY, nullptr, true); - } - else - BossAI::MoveInLineOfSight(who); + _Reset(); + zombieToBeEatenGUID.Clear(); + state = STATE_GLUTH_NORMAL; + me->SetReactState(REACT_AGGRESSIVE); + me->SetSpeed(UnitMoveType::MOVE_RUN, 12.0f); } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); - events.ScheduleEvent(EVENT_WOUND, 10000); - events.ScheduleEvent(EVENT_ENRAGE, 15000); - events.ScheduleEvent(EVENT_DECIMATE, 105000); - events.ScheduleEvent(EVENT_BERSERK, 8*60000); - events.ScheduleEvent(EVENT_SUMMON, 15000); + events.ScheduleEvent(EVENT_WOUND, Seconds(10)); + events.ScheduleEvent(EVENT_ENRAGE, randtime(Seconds(16), Seconds(22))); + events.ScheduleEvent(EVENT_DECIMATE, randtime(Minutes(1)+Seconds(50), Minutes(2))); + events.ScheduleEvent(EVENT_BERSERK, Minutes(8)); + events.ScheduleEvent(EVENT_SUMMON, Seconds(15)); + events.ScheduleEvent(EVENT_SEARCH_ZOMBIE_SINGLE, Seconds(12)); } - void JustSummoned(Creature* summon) override + void SummonedCreatureDies(Creature* summoned, Unit* /* who */) override { - if (summon->GetEntry() == NPC_ZOMBIE) - summon->AI()->AttackStart(me); - summons.Summon(summon); + summons.Despawn(summoned); // needed or else dead zombies not despawned yet will still be in the list } void UpdateAI(uint32 diff) override { - if (!UpdateVictimWithGaze()) + if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_WOUND: + if (state == STATE_GLUTH_EATING) + { + events.Repeat(Seconds(3)); + break; + } + DoCastVictim(SPELL_MORTAL_WOUND); - events.ScheduleEvent(EVENT_WOUND, 10000); + events.Repeat(Seconds(10)); break; case EVENT_ENRAGE: - /// @todo Add missing text + if (state == STATE_GLUTH_EATING) + { + events.Repeat(Seconds(5)); + break; + } + + Talk(EMOTE_ENRAGE); DoCast(me, SPELL_ENRAGE); - events.ScheduleEvent(EVENT_ENRAGE, 15000); + events.Repeat(randtime(Seconds(16), Seconds(22))); break; case EVENT_DECIMATE: - /// @todo Add missing text + if (state == STATE_GLUTH_EATING) + { + events.Repeat(Seconds(4)); + break; + } + + Talk(EMOTE_DECIMATE); DoCastAOE(SPELL_DECIMATE); - events.ScheduleEvent(EVENT_DECIMATE, 105000); + for (int i = 1; i <= 20; i++) + events.ScheduleEvent(EVENT_SEARCH_ZOMBIE_MULTI, Seconds(3*i)); + events.ScheduleEvent(EVENT_DECIMATE, randtime(Minutes(1)+Seconds(50), Minutes(2))); break; case EVENT_BERSERK: + Talk(EMOTE_BERSERKER); DoCast(me, SPELL_BERSERK); - events.ScheduleEvent(EVENT_BERSERK, 5*60000); + events.Repeat(Minutes(5)); //refresh the hard enrage buff break; case EVENT_SUMMON: - for (int32 i = 0; i < RAID_MODE(1, 2); ++i) - DoSummon(NPC_ZOMBIE, PosSummon[rand32() % RAID_MODE(1, 3)]); - events.ScheduleEvent(EVENT_SUMMON, 10000); + if (Is25ManRaid()) // one wave each 10s. one wave=1 zombie in 10man and 2 zombies in 25man. + me->SummonCreatureGroup(SUMMON_GROUP_CHOW_25MAN); + else + me->SummonCreatureGroup(SUMMON_GROUP_CHOW_10MAN); + events.Repeat(Seconds(10)); + break; + case EVENT_SEARCH_ZOMBIE_SINGLE: + { + Creature* zombie = nullptr; + for (SummonList::const_iterator itr = summons.begin(); !zombie && itr != summons.end(); ++itr) + { + zombie=ObjectAccessor::GetCreature(*me, *itr); + if (!zombie || !zombie->IsAlive() || !zombie->IsWithinDistInMap(me, 10.0)) + zombie = nullptr; + } + + if (zombie) + { + zombieToBeEatenGUID = zombie->GetGUID(); // save for later use + + // the soon-to-be-eaten zombie should stop moving and stop attacking + zombie->AI()->SetData(DATA_ZOMBIE_STATE, STATE_ZOMBIE_TOBE_EATEN); + + // gluth should stop AAs on his primary target and turn toward the zombie (2 yards away). He then pauses for a few seconds. + me->SetSpeed(MOVE_RUN, 36.0f); + + me->SetReactState(ReactStates::REACT_PASSIVE); + me->AttackStop(); + + Talk(EMOTE_SPOTS_ONE); + + //me->SetTarget(ObjectGuid::Empty); + + me->GetMotionMaster()->MoveCloserAndStop(1, zombie, 2.0f); + + state = STATE_GLUTH_EATING; + } + + events.Repeat(RAID_MODE(Seconds(7), Seconds(5))); + break; + } + case EVENT_KILL_ZOMBIE_SINGLE: + { + Creature* zombieToBeEaten = ObjectAccessor::GetCreature(*me, zombieToBeEatenGUID); + if (zombieToBeEaten && zombieToBeEaten->IsAlive() && zombieToBeEaten->IsWithinDistInMap(me, 10.0)) + DoCast(zombieToBeEaten, SPELL_ZOMBIE_CHOW_SEARCH_SINGLE); // do the killing + healing in done inside by spell script see below. + + zombieToBeEatenGUID = ObjectGuid::Empty; + state = STATE_GLUTH_NORMAL; + me->SetSpeed(UnitMoveType::MOVE_RUN, 12.0f); + + // and then return on primary target + me->SetReactState(REACT_AGGRESSIVE); + + break; + } + case EVENT_SEARCH_ZOMBIE_MULTI: + { + if (state == STATE_GLUTH_EATING) // skip and simply wait for the next occurence + break; + + Creature* zombie = nullptr; + for (SummonList::const_iterator itr = summons.begin(); !zombie && itr != summons.end(); ++itr) + { + zombie = ObjectAccessor::GetCreature(*me, *itr); + if (zombie && zombie->IsAlive() && zombie->GetExactDist2d(me) > 18.0) + zombie = nullptr; + } + + if (zombie) // cast the aoe spell only if at least one zombie is found nearby + { + Talk(EMOTE_DEVOURS_ALL); + DoCastAOE(SPELL_ZOMBIE_CHOW_SEARCH_MULTI); + } break; + } } } - if (me->GetVictim() && me->EnsureVictim()->GetEntry() == NPC_ZOMBIE) + DoMeleeAttackIfReady(); + } + + void MovementInform(uint32 /*type*/, uint32 id) override + { + if (id == 1){ + me->GetMotionMaster()->MoveIdle(); + events.ScheduleEvent(EVENT_KILL_ZOMBIE_SINGLE, Seconds(1)); + } + + } + + void DoAction(int32 action) override + { + switch (action) + { + case ACTION_DECIMATE_EVENT: + for (ObjectGuid zombieGuid : summons) + { + Creature* zombie = ObjectAccessor::GetCreature(*me, zombieGuid); + if (zombie && zombie->IsAlive()) + zombie->AI()->SetData(DATA_ZOMBIE_STATE, STATE_ZOMBIE_DECIMATED); + } + break; + } + } + + private: + ObjectGuid zombieToBeEatenGUID; + uint8 state; + }; + +}; + +// spell 28374 (10man) / 54426 (25man) - Decimate +class spell_gluth_decimate : public SpellScriptLoader +{ +public: + spell_gluth_decimate() : SpellScriptLoader("spell_gluth_decimate") { } + + class spell_gluth_decimate_SpellScript : public SpellScript + { + PrepareSpellScript(spell_gluth_decimate_SpellScript); + + // handles the damaging effect of the decimate spell. + void HandleScriptEffect(SpellEffIndex /* index */) + { + if (Unit *unit = GetHitUnit()) { - if (me->IsWithinMeleeRange(me->GetVictim())) + int32 damage = int32(unit->GetHealth()) - int32(unit->CountPctFromMaxHealth(5)); + if (damage > 0) + GetCaster()->CastCustomSpell(SPELL_DECIMATE_DMG, SPELLVALUE_BASE_POINT0, damage, unit); + } + } + + // handles the change of zombies behavior after the decimate spell + void HandleEvent(SpellEffIndex /* index */) + { + GetCaster()->GetAI()->DoAction(ACTION_DECIMATE_EVENT); + } + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + return (sSpellMgr->GetSpellInfo(SPELL_DECIMATE_DMG) != nullptr); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_gluth_decimate_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + OnEffectHit += SpellEffectFn(spell_gluth_decimate_SpellScript::HandleEvent, EFFECT_2, SPELL_EFFECT_SEND_EVENT); + } + + bool Load() override + { + return GetCaster() && GetCaster()->GetEntry() == NPC_GLUTH; + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_gluth_decimate_SpellScript(); + } + +}; + +// used by both 28239 & 28404 (single target and aoe zombie-kill spell) to heal Gluth on each target hit. + +class spell_gluth_zombiechow_search : public SpellScriptLoader +{ +public: + spell_gluth_zombiechow_search() : SpellScriptLoader("spell_gluth_zombiechow_search") { } + + class spell_gluth_zombiechow_search_SpellScript : public SpellScript + { + PrepareSpellScript(spell_gluth_zombiechow_search_SpellScript); + + void HealForEachTargetHit() + { + GetCaster()->ModifyHealth(int32(GetCaster()->CountPctFromMaxHealth(5))); + } + + void Register() override + { + AfterHit += SpellHitFn(spell_gluth_zombiechow_search_SpellScript::HealForEachTargetHit); + } + + bool Load() override + { + return GetCaster() && GetCaster()->GetEntry() == NPC_GLUTH; + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_gluth_zombiechow_search_SpellScript(); + } + +}; + +// creature 16360 (10man) / 30303 (25man) +class npc_zombie_chow : public CreatureScript +{ +public: + + npc_zombie_chow() : CreatureScript("npc_zombie_chow") { } + + struct npc_zombie_chowAI : public ScriptedAI + { + npc_zombie_chowAI(Creature* creature) : ScriptedAI(creature) + { + GluthGUID = creature->GetInstanceScript()->GetGuidData(DATA_GLUTH); + + DoCast(me, SPELL_INFECTED_WOUND); + timer = 0; + state = STATE_ZOMBIE_NORMAL; + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + if (state == STATE_ZOMBIE_DECIMATED) + { + timer += diff; + if (Creature* gluth = ObjectAccessor::GetCreature(*me, GluthGUID)) { - me->Kill(me->GetVictim()); - me->ModifyHealth(int32(me->CountPctFromMaxHealth(5))); + // Putting this in the UpdateAI loop fixes an issue where death gripping a decimated zombie would make the zombie stand still until the rest of the fight. + // Also fix the issue where if one or more zombie is rooted when decimates hits (and MovePoint() is called), the zombie teleport to the boss. pretty weird behavior. + if (timer > 1600 && me->GetExactDist2d(gluth) > 10.0f && me->CanFreeMove()) // it takes about 1600 ms for the animation to cycle. This way, the animation looks relatively smooth. + { + me->GetMotionMaster()->MovePoint(0, gluth->GetPosition()); // isn't dynamic. So, to take into account Gluth's movement, it must be called periodicly. + timer = 0; + } + + if (me->GetExactDist2d(gluth) <= 10.0f) + me->StopMoving(); } } - else + else if (state == STATE_ZOMBIE_NORMAL) DoMeleeAttackIfReady(); } + + void SetData(uint32 id, uint32 value) override + { + if (id == DATA_ZOMBIE_STATE) // change of state + { + state = value; + if (value == STATE_ZOMBIE_DECIMATED) + { + me->SetReactState(ReactStates::REACT_PASSIVE); + me->AttackStop(); + me->SetTarget(ObjectGuid::Empty); + // at this point, the zombie should be non attacking and non moving. + + me->SetWalk(true); // it doesnt seem to work with MoveFollow() (but it does work with MovePoint()). + + timer = 1000; + } + else if (value == STATE_ZOMBIE_TOBE_EATEN) + { + // forced to stand still + me->GetMotionMaster()->Clear(); + me->StopMoving(); + + // and loose aggro behavior + me->SetReactState(ReactStates::REACT_PASSIVE); + me->AttackStop(); + me->SetTarget(ObjectGuid::Empty); + + me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); // not sure if this is blizz-like but this is very convenient + } + } + } + + uint32 GetData(uint32 index) const override + { + if (index == DATA_ZOMBIE_STATE) + return state; + return 0; + } + + private: + uint32 timer; + uint8 state; + ObjectGuid GluthGUID; }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<npc_zombie_chowAI>(creature); + } }; void AddSC_boss_gluth() { new boss_gluth(); + new spell_gluth_decimate(); + new spell_gluth_zombiechow_search(); + new npc_zombie_chow(); } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp index 81f1e071da0..30c05c9dca9 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp @@ -65,7 +65,7 @@ enum Spells /* gothik phase two spells */ SPELL_HARVEST_SOUL = 28679, SPELL_SHADOW_BOLT = 29317, - + /* visual spells */ SPELL_ANCHOR_1_TRAINEE = 27892, SPELL_ANCHOR_1_DK = 27928, @@ -324,13 +324,13 @@ class boss_gothik : public CreatureScript { _EnterCombat(); events.SetPhase(PHASE_ONE); - events.ScheduleEvent(EVENT_SUMMON, 25 * IN_MILLISECONDS, 0, PHASE_ONE); - events.ScheduleEvent(EVENT_DOORS_UNLOCK, 205 * IN_MILLISECONDS, 0, PHASE_ONE); - events.ScheduleEvent(EVENT_PHASE_TWO, 270 * IN_MILLISECONDS, 0, PHASE_ONE); + events.ScheduleEvent(EVENT_SUMMON, Seconds(25), 0, PHASE_ONE); + events.ScheduleEvent(EVENT_DOORS_UNLOCK, Minutes(3) + Seconds(25), 0, PHASE_ONE); + events.ScheduleEvent(EVENT_PHASE_TWO, Minutes(4) + Seconds(30), 0, PHASE_ONE); Talk(SAY_INTRO_1); - events.ScheduleEvent(EVENT_INTRO_2, 4 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_INTRO_3, 9 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_INTRO_4, 14 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_INTRO_2, Seconds(4)); + events.ScheduleEvent(EVENT_INTRO_3, Seconds(9)); + events.ScheduleEvent(EVENT_INTRO_4, Seconds(14)); instance->SetData(DATA_GOTHIK_GATE, GO_STATE_READY); _gateIsOpen = false; } @@ -373,10 +373,14 @@ class boss_gothik : public CreatureScript instance->SetData(DATA_GOTHIK_GATE, GO_STATE_ACTIVE); Talk(EMOTE_GATE_OPENED); _gateIsOpen = true; - + for (ObjectGuid summonGuid : summons) + { if (Creature* summon = ObjectAccessor::GetCreature(*me, summonGuid)) summon->AI()->DoAction(ACTION_GATE_OPENED); + if (summons.empty()) // ACTION_GATE_OPENED may cause an evade, despawning summons and invalidating our iterator + break; + } } void DamageTaken(Unit* /*who*/, uint32& damage) override @@ -440,7 +444,7 @@ class boss_gothik : public CreatureScript TC_LOG_INFO("scripts", "GothikAI: Wave count %d is out of range for difficulty %d.", _waveCount, GetDifficulty()); break; } - + std::list<Creature*> triggers; me->GetCreatureListWithEntryInGrid(triggers, NPC_TRIGGER, 150.0f); for (GothikWaveEntry entry : RAID_MODE(waves10, waves25)[_waveCount].first) @@ -466,7 +470,7 @@ class boss_gothik : public CreatureScript default: targetDBGuid = 0; } - + for (Creature* trigger : triggers) if (trigger && trigger->GetSpawnId() == targetDBGuid) { @@ -476,7 +480,7 @@ class boss_gothik : public CreatureScript } if (uint8 timeToNext = RAID_MODE(waves10, waves25)[_waveCount].second) - events.ScheduleEvent(EVENT_SUMMON, timeToNext * IN_MILLISECONDS, 0, PHASE_ONE); + events.Repeat(Seconds(timeToNext)); ++_waveCount; break; @@ -493,9 +497,9 @@ class boss_gothik : public CreatureScript break; case EVENT_PHASE_TWO: events.SetPhase(PHASE_TWO); - events.ScheduleEvent(EVENT_TELEPORT, 20 * IN_MILLISECONDS, 0, PHASE_TWO); - events.ScheduleEvent(EVENT_HARVEST, 15 * IN_MILLISECONDS, 0, PHASE_TWO); - events.ScheduleEvent(EVENT_RESUME_ATTACK, 2 * IN_MILLISECONDS, 0, PHASE_TWO); + events.ScheduleEvent(EVENT_TELEPORT, Seconds(20), 0, PHASE_TWO); + events.ScheduleEvent(EVENT_HARVEST, Seconds(15), 0, PHASE_TWO); + events.ScheduleEvent(EVENT_RESUME_ATTACK, Seconds(2), 0, PHASE_TWO); Talk(SAY_PHASE_TWO); Talk(EMOTE_PHASE_TWO); me->SetReactState(REACT_PASSIVE); @@ -514,23 +518,23 @@ class boss_gothik : public CreatureScript _lastTeleportDead = !_lastTeleportDead; events.CancelEvent(EVENT_BOLT); - events.ScheduleEvent(EVENT_TELEPORT, 20 * IN_MILLISECONDS, 0, PHASE_TWO); events.ScheduleEvent(EVENT_RESUME_ATTACK, 2 * IN_MILLISECONDS, 0, PHASE_TWO); + events.Repeat(Seconds(20)); } break; case EVENT_HARVEST: DoCastAOE(SPELL_HARVEST_SOUL, true); // triggered allows this to go "through" shadow bolt - events.ScheduleEvent(EVENT_HARVEST, 15 * IN_MILLISECONDS, 0, PHASE_TWO); + events.Repeat(Seconds(15)); break; case EVENT_RESUME_ATTACK: me->SetReactState(REACT_AGGRESSIVE); - events.ScheduleEvent(EVENT_BOLT, 0, 0, PHASE_TWO); + events.ScheduleEvent(EVENT_BOLT, Seconds(0), 0, PHASE_TWO); // return to the start of this method so victim side etc is re-evaluated return UpdateAI(0u); // tail recursion for efficiency case EVENT_BOLT: DoCastVictim(SPELL_SHADOW_BOLT); - events.ScheduleEvent(EVENT_BOLT, 1 * IN_MILLISECONDS, 0, PHASE_TWO); + events.Repeat(Seconds(2)); break; case EVENT_INTRO_2: Talk(SAY_INTRO_2); @@ -544,7 +548,7 @@ class boss_gothik : public CreatureScript } } } - + private: uint32 _waveCount; bool _gateCanOpen; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp index a1d8f6e5e02..cf38d659d40 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp @@ -57,10 +57,10 @@ class boss_grobbulus : public CreatureScript void EnterCombat(Unit* /*who*/) override { _EnterCombat(); - events.ScheduleEvent(EVENT_CLOUD, 15000); - events.ScheduleEvent(EVENT_INJECT, 20000); - events.ScheduleEvent(EVENT_SPRAY, urand(15000, 30000)); // not sure - events.ScheduleEvent(EVENT_BERSERK, 12 * 60000); + events.ScheduleEvent(EVENT_CLOUD, Seconds(15)); + events.ScheduleEvent(EVENT_INJECT, Seconds(20)); + events.ScheduleEvent(EVENT_SPRAY, randtime(Seconds(15), Seconds(30))); // not sure + events.ScheduleEvent(EVENT_BERSERK, Minutes(12)); } void SpellHitTarget(Unit* target, SpellInfo const* spell) override @@ -82,19 +82,19 @@ class boss_grobbulus : public CreatureScript { case EVENT_CLOUD: DoCastAOE(SPELL_POISON_CLOUD); - events.ScheduleEvent(EVENT_CLOUD, 15000); + events.Repeat(Seconds(15)); return; case EVENT_BERSERK: DoCastAOE(SPELL_BERSERK, true); return; case EVENT_SPRAY: DoCastAOE(SPELL_SLIME_SPRAY); - events.ScheduleEvent(EVENT_SPRAY, urand(15000, 30000)); + events.Repeat(randtime(Seconds(15), Seconds(30))); return; case EVENT_INJECT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true, -SPELL_MUTATING_INJECTION)) DoCast(target, SPELL_MUTATING_INJECTION); - events.ScheduleEvent(EVENT_INJECT, 8000 + uint32(120 * me->GetHealthPct())); + events.Repeat(Seconds(8) + Milliseconds(uint32(std::round(120 * me->GetHealthPct())))); return; default: break; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp index 9b9619fe5b9..41d718d188d 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp @@ -27,6 +27,7 @@ enum Spells SPELL_SPELL_DISRUPTION = 29310, SPELL_PLAGUE_CLOUD = 29350, SPELL_TELEPORT_SELF = 30211, + SPELL_ERUPTION = 29371 }; enum Yells @@ -60,6 +61,15 @@ enum Misc DATA_SAFETY_DANCE = 19962139 }; +static const uint32 firstEruptionDBGUID = 84980; +static const uint8 numSections = 4; +static const uint8 numEruptions[numSections] = { // count of sequential GO DBGUIDs in the respective section of the room + 15, + 25, + 23, + 13 +}; + class boss_heigan : public CreatureScript { public: @@ -72,7 +82,7 @@ public: struct boss_heiganAI : public BossAI { - boss_heiganAI(Creature* creature) : BossAI(creature, BOSS_HEIGAN), eruptSection(0), eruptDirection(false), safetyDance(false) { } + boss_heiganAI(Creature* creature) : BossAI(creature, BOSS_HEIGAN), _safeSection(0), _danceDirection(false), _safetyDance(false) { } void Reset() override { @@ -82,15 +92,16 @@ public: void KilledUnit(Unit* who) override { - Talk(SAY_SLAY); - if (who->GetTypeId() == TYPEID_PLAYER) - safetyDance = false; + { + Talk(SAY_SLAY); + _safetyDance = false; + } } uint32 GetData(uint32 type) const override { - return (type == DATA_SAFETY_DANCE && safetyDance) ? 1u : 0u; + return (type == DATA_SAFETY_DANCE && _safetyDance) ? 1u : 0u; } void JustDied(Unit* /*killer*/) override @@ -104,13 +115,27 @@ public: _EnterCombat(); Talk(SAY_AGGRO); - eruptSection = 3; - events.ScheduleEvent(EVENT_DISRUPT, urand(15 * IN_MILLISECONDS, 20 * IN_MILLISECONDS), 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_FEVER, urand(10 * IN_MILLISECONDS, 20 * IN_MILLISECONDS), 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_DANCE, 90 * IN_MILLISECONDS, 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_ERUPT, 15 * IN_MILLISECONDS, 0, PHASE_FIGHT); + _safeSection = 0; + events.ScheduleEvent(EVENT_DISRUPT, randtime(Seconds(15), Seconds(20)), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_FEVER, randtime(Seconds(10), Seconds(20)), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_DANCE, Minutes(1) + Seconds(30), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_ERUPT, Seconds(15), 0, PHASE_FIGHT); + + _safetyDance = true; - safetyDance = true; + // figure out the current GUIDs of our eruption tiles and which segment they belong in + std::unordered_multimap<uint32, GameObject*> const& mapGOs = me->GetMap()->GetGameObjectBySpawnIdStore(); + uint32 spawnId = firstEruptionDBGUID; + for (uint8 section = 0; section < numSections; ++section) + { + _eruptTiles[section].clear(); + for (uint8 i = 0; i < numEruptions[section]; ++i) + { + std::pair<std::unordered_multimap<uint32, GameObject*>::const_iterator, std::unordered_multimap<uint32, GameObject*>::const_iterator> tileIt = mapGOs.equal_range(spawnId++); + for (std::unordered_multimap<uint32, GameObject*>::const_iterator it = tileIt.first; it != tileIt.second; ++it) + _eruptTiles[section].push_back(it->second->GetGUID()); + } + } } void UpdateAI(uint32 diff) override @@ -126,52 +151,56 @@ public: { case EVENT_DISRUPT: DoCastAOE(SPELL_SPELL_DISRUPTION); - events.ScheduleEvent(EVENT_DISRUPT, 11 * IN_MILLISECONDS); + events.Repeat(Seconds(11)); break; case EVENT_FEVER: DoCastAOE(SPELL_DECREPIT_FEVER); - events.ScheduleEvent(EVENT_FEVER, urand(20 * IN_MILLISECONDS, 25 * IN_MILLISECONDS)); + events.Repeat(randtime(Seconds(20), Seconds(25))); break; case EVENT_DANCE: events.SetPhase(PHASE_DANCE); Talk(SAY_TAUNT); Talk(EMOTE_DANCE); - eruptSection = 3; + _safeSection = 0; me->SetReactState(REACT_PASSIVE); me->AttackStop(); me->StopMoving(); DoCast(SPELL_TELEPORT_SELF); DoCastAOE(SPELL_PLAGUE_CLOUD); - events.ScheduleEvent(EVENT_DANCE_END, 45 * IN_MILLISECONDS, 0, PHASE_DANCE); - events.ScheduleEvent(EVENT_ERUPT, 10 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_DANCE_END, Seconds(45), 0, PHASE_DANCE); + events.ScheduleEvent(EVENT_ERUPT, Seconds(10)); break; case EVENT_DANCE_END: events.SetPhase(PHASE_FIGHT); Talk(EMOTE_DANCE_END); - eruptSection = 3; - events.ScheduleEvent(EVENT_DISRUPT, urand(10, 25) * IN_MILLISECONDS, 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_FEVER, urand(15, 20) * IN_MILLISECONDS, 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_DANCE, 90 * IN_MILLISECONDS, 0, PHASE_FIGHT); - events.ScheduleEvent(EVENT_ERUPT, 15 * IN_MILLISECONDS, 0, PHASE_FIGHT); + _safeSection = 0; + events.ScheduleEvent(EVENT_DISRUPT, randtime(Seconds(10), Seconds(25)), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_FEVER, randtime(Seconds(15), Seconds(20)), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_DANCE, Minutes(1) + Seconds(30), 0, PHASE_FIGHT); + events.ScheduleEvent(EVENT_ERUPT, Seconds(15), 0, PHASE_FIGHT); me->CastStop(); me->SetReactState(REACT_AGGRESSIVE); DoZoneInCombat(); break; case EVENT_ERUPT: - instance->SetData(DATA_HEIGAN_ERUPT, eruptSection); TeleportCheaters(); - - if (eruptSection == 0) - eruptDirection = true; - else if (eruptSection == 3) - eruptDirection = false; - - eruptDirection ? ++eruptSection : --eruptSection; - - if (events.IsInPhase(PHASE_DANCE)) - events.ScheduleEvent(EVENT_ERUPT, 3 * IN_MILLISECONDS, 0, PHASE_DANCE); - else - events.ScheduleEvent(EVENT_ERUPT, 10 * IN_MILLISECONDS, 0, PHASE_FIGHT); + for (uint8 section = 0; section < numSections; ++section) + if (section != _safeSection) + for (ObjectGuid tileGUID : _eruptTiles[section]) + if (GameObject* tile = ObjectAccessor::GetGameObject(*me, tileGUID)) + { + tile->SendCustomAnim(0); + tile->CastSpell(nullptr, SPELL_ERUPTION); + } + + if (_safeSection == 0) + _danceDirection = true; + else if (_safeSection == numSections-1) + _danceDirection = false; + + _danceDirection ? ++_safeSection : --_safeSection; + + events.Repeat(events.IsInPhase(PHASE_DANCE) ? Seconds(3) : Seconds(10)); break; } } @@ -180,10 +209,11 @@ public: } private: - uint32 eruptSection; - bool eruptDirection; + std::vector<ObjectGuid> _eruptTiles[numSections]; // populated on encounter start - bool safetyDance; // is achievement still possible? (= no player deaths yet) + uint32 _safeSection; // 0 is next to the entrance + bool _danceDirection; // true is counter-clockwise, false is clock-wise + bool _safetyDance; // is achievement still possible? (= no player deaths yet) }; }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp index 47807ec28cb..42efdfbfe67 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp @@ -309,7 +309,7 @@ public: _Reset(); me->setFaction(35); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NOT_SELECTABLE); ResetPlayerScale(); spawns.DespawnAll(); @@ -356,7 +356,7 @@ public: } DoCast(me, SPELL_KELTHUZAD_CHANNEL, false); Talk(SAY_SUMMON_MINIONS); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NOT_SELECTABLE); me->SetFloatValue(UNIT_FIELD_COMBATREACH, 4); me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 4); events.SetPhase(PHASE_ONE); @@ -426,7 +426,7 @@ public: Talk(SAY_AGGRO); Talk(EMOTE_PHASE_TWO); spawns.DespawnAll(); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NOT_SELECTABLE); me->CastStop(); DoStartMovement(me->GetVictim()); diff --git a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp index 086d21120e8..c6c9c76bed4 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp @@ -24,7 +24,6 @@ enum Spells { SPELL_NECROTIC_AURA = 55593, - SPELL_WARN_NECROTIC_AURA = 59481, SPELL_SUMMON_SPORE = 29234, SPELL_DEATHBLOOM = 29865, SPELL_INEVITABLE_DOOM = 29204, @@ -42,11 +41,12 @@ enum Texts enum Events { - EVENT_NECROTIC_AURA = 1, - EVENT_DEATHBLOOM = 2, - EVENT_INEVITABLE_DOOM = 3, - EVENT_SPORE = 4, - EVENT_NECROTIC_AURA_FADING = 5, + EVENT_NECROTIC_AURA = 1, + EVENT_DEATHBLOOM, + EVENT_INEVITABLE_DOOM, + EVENT_SPORE, + EVENT_NECROTIC_AURA_FADING, + EVENT_NECROTIC_AURA_FADED }; enum Achievement @@ -82,10 +82,10 @@ class boss_loatheb : public CreatureScript void EnterCombat(Unit* /*who*/) override { _EnterCombat(); - events.ScheduleEvent(EVENT_NECROTIC_AURA, 17 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_DEATHBLOOM, 5 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_SPORE, RAID_MODE(36,18) * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_INEVITABLE_DOOM, 2 * MINUTE * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_NECROTIC_AURA, Seconds(17)); + events.ScheduleEvent(EVENT_DEATHBLOOM, Seconds(5)); + events.ScheduleEvent(EVENT_SPORE, Seconds(18)); + events.ScheduleEvent(EVENT_INEVITABLE_DOOM, Minutes(2)); } void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override @@ -94,13 +94,6 @@ class boss_loatheb : public CreatureScript summon->CastSpell(summon,SPELL_FUNGAL_CREEP,true); } - void SummonedCreatureDespawn(Creature* summon) override - { - summons.Despawn(summon); - if (summon->IsAlive()) - summon->CastSpell(summon,SPELL_FUNGAL_CREEP,true); - } - uint32 GetData(uint32 id) const override { return (_sporeLoserData && id == DATA_ACHIEVEMENT_SPORE_LOSER) ? 1u : 0u; @@ -119,34 +112,33 @@ class boss_loatheb : public CreatureScript { case EVENT_NECROTIC_AURA: DoCastAOE(SPELL_NECROTIC_AURA); - DoCast(me, SPELL_WARN_NECROTIC_AURA); - events.ScheduleEvent(EVENT_NECROTIC_AURA, 20 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_NECROTIC_AURA_FADING, 14 * IN_MILLISECONDS); + Talk(SAY_NECROTIC_AURA_APPLIED); + events.ScheduleEvent(EVENT_NECROTIC_AURA_FADING, Seconds(14)); + events.ScheduleEvent(EVENT_NECROTIC_AURA_FADED, Seconds(17)); + events.Repeat(Seconds(20)); break; case EVENT_DEATHBLOOM: DoCastAOE(SPELL_DEATHBLOOM); - events.ScheduleEvent(EVENT_DEATHBLOOM, 30 * IN_MILLISECONDS); + events.Repeat(Seconds(30)); break; case EVENT_INEVITABLE_DOOM: _doomCounter++; DoCastAOE(SPELL_INEVITABLE_DOOM); if (_doomCounter > 6) - { - if (_doomCounter & 1) // odd - events.ScheduleEvent(EVENT_INEVITABLE_DOOM, 14 * IN_MILLISECONDS); - else - events.ScheduleEvent(EVENT_INEVITABLE_DOOM, 17 * IN_MILLISECONDS); - } + events.Repeat((_doomCounter & 1) ? Seconds(14) : Seconds(17)); else - events.ScheduleEvent(EVENT_INEVITABLE_DOOM, 30 * IN_MILLISECONDS); + events.Repeat(30); break; case EVENT_SPORE: DoCast(me, SPELL_SUMMON_SPORE, false); - events.ScheduleEvent(EVENT_SPORE, RAID_MODE(36,18) * IN_MILLISECONDS); + events.Repeat(RAID_MODE(Seconds(36), Seconds(15))); break; case EVENT_NECROTIC_AURA_FADING: Talk(SAY_NECROTIC_AURA_FADING); break; + case EVENT_NECROTIC_AURA_FADED: + Talk(SAY_NECROTIC_AURA_REMOVED); + break; default: break; } @@ -177,49 +169,6 @@ class achievement_spore_loser : public AchievementCriteriaScript } }; -typedef boss_loatheb::boss_loathebAI LoathebAI; - -class spell_loatheb_necrotic_aura_warning : public SpellScriptLoader -{ - public: - spell_loatheb_necrotic_aura_warning() : SpellScriptLoader("spell_loatheb_necrotic_aura_warning") { } - - class spell_loatheb_necrotic_aura_warning_AuraScript : public AuraScript - { - PrepareAuraScript(spell_loatheb_necrotic_aura_warning_AuraScript); - - bool Validate(SpellInfo const* /*spell*/) override - { - if (!sSpellStore.LookupEntry(SPELL_WARN_NECROTIC_AURA)) - return false; - return true; - } - - void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) - { - if (GetTarget()->IsAIEnabled) - ENSURE_AI(LoathebAI, GetTarget()->GetAI())->Talk(SAY_NECROTIC_AURA_APPLIED); - } - - void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) - { - if (GetTarget()->IsAIEnabled) - ENSURE_AI(LoathebAI, GetTarget()->GetAI())->Talk(SAY_NECROTIC_AURA_REMOVED); - } - - void Register() override - { - AfterEffectApply += AuraEffectApplyFn(spell_loatheb_necrotic_aura_warning_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); - AfterEffectRemove += AuraEffectRemoveFn(spell_loatheb_necrotic_aura_warning_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); - } - }; - - AuraScript* GetAuraScript() const override - { - return new spell_loatheb_necrotic_aura_warning_AuraScript(); - } -}; - class spell_loatheb_deathbloom : public SpellScriptLoader { public: @@ -260,6 +209,5 @@ void AddSC_boss_loatheb() { new boss_loatheb(); new achievement_spore_loser(); - new spell_loatheb_necrotic_aura_warning(); new spell_loatheb_deathbloom(); } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp index 9d8f1365afb..9502193884a 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp @@ -73,6 +73,8 @@ struct WebTargetSelector : public std::unary_function<Unit*, bool> WebTargetSelector(Unit* maexxna) : _maexxna(maexxna) {} bool operator()(Unit const* target) const { + if (target->GetTypeId() != TYPEID_PLAYER) // never web nonplayers (pets, guardians, etc.) + return false; if (_maexxna->GetVictim() == target) // never target tank return false; if (target->HasAura(SPELL_WEB_WRAP)) // never target targets that are already webbed @@ -101,11 +103,11 @@ public: void EnterCombat(Unit* /*who*/) override { _EnterCombat(); - events.ScheduleEvent(EVENT_WRAP, 20 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_SPRAY, 40 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_SHOCK, urandms(5, 10)); - events.ScheduleEvent(EVENT_POISON, urandms(10, 15)); - events.ScheduleEvent(EVENT_SUMMON, 30 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_WRAP, Seconds(20)); + events.ScheduleEvent(EVENT_SPRAY, Seconds(40)); + events.ScheduleEvent(EVENT_SHOCK, randtime(Seconds(5), Seconds(10))); + events.ScheduleEvent(EVENT_POISON, randtime(Seconds(10), Seconds(15))); + events.ScheduleEvent(EVENT_SUMMON, Seconds(30)); } void Reset() override @@ -153,28 +155,28 @@ public: } } } - events.ScheduleEvent(EVENT_WRAP, 40000); + events.Repeat(Seconds(40)); break; } case EVENT_SPRAY: Talk(EMOTE_WEB_SPRAY); DoCastAOE(SPELL_WEB_SPRAY); - events.ScheduleEvent(EVENT_SPRAY, 40000); + events.Repeat(Seconds(40)); break; case EVENT_SHOCK: DoCastAOE(SPELL_POISON_SHOCK); - events.ScheduleEvent(EVENT_SHOCK, urandms(10, 20)); + events.Repeat(randtime(Seconds(10), Seconds(20))); break; case EVENT_POISON: DoCastVictim(SPELL_NECROTIC_POISON); - events.ScheduleEvent(EVENT_POISON, urandms(10, 20)); + events.Repeat(randtime(Seconds(10), Seconds(20))); break; case EVENT_SUMMON: Talk(EMOTE_SPIDERS); uint8 amount = urand(8, 10); for (uint8 i = 0; i < amount; ++i) DoSummon(NPC_SPIDERLING, me, 4.0f, 5 * IN_MILLISECONDS, TEMPSUMMON_CORPSE_TIMED_DESPAWN); - events.ScheduleEvent(EVENT_SUMMON, 40000); + events.Repeat(Seconds(40)); break; } } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp index 8ee3936dee3..2108b4ce102 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp @@ -131,25 +131,25 @@ public: Reset(); else { - uint8 secondsGround; + uint8 timeGround; switch (balconyCount) { case 0: - secondsGround = 90; + timeGround = 90; break; case 1: - secondsGround = 110; + timeGround = 110; break; case 2: default: - secondsGround = 180; + timeGround = 180; } - events.ScheduleEvent(EVENT_GROUND_ATTACKABLE, 2 * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_BALCONY, secondsGround * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_CURSE, urand(10,25) * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_WARRIOR, urand(20,30) * IN_MILLISECONDS, 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_GROUND_ATTACKABLE, Seconds(2), 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_BALCONY, Seconds(timeGround), 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_CURSE, randtime(Seconds(10), Seconds(25)), 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_WARRIOR, randtime(Seconds(20), Seconds(30)), 0, PHASE_GROUND); if (GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) - events.ScheduleEvent(EVENT_BLINK, urand(20,30) * IN_MILLISECONDS, 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_BLINK, randtime(Seconds(20), Seconds(30)), 0, PHASE_GROUND); } } @@ -220,7 +220,7 @@ public: case EVENT_CURSE: { DoCastAOE(SPELL_CURSE); - events.ScheduleEvent(EVENT_CURSE, urand(50, 70) * IN_MILLISECONDS, 0, PHASE_GROUND); + events.Repeat(randtime(Seconds(50), Seconds(70))); break; } case EVENT_WARRIOR: @@ -229,7 +229,7 @@ public: CastSummon(RAID_MODE(2, 3), 0, 0); - events.ScheduleEvent(EVENT_WARRIOR, 40 * IN_MILLISECONDS, 0, PHASE_GROUND); + events.Repeat(Seconds(40)); break; case EVENT_BLINK: DoCastAOE(SPELL_CRIPPLE, true); @@ -237,7 +237,7 @@ public: DoResetThreat(); justBlinked = true; - events.ScheduleEvent(EVENT_BLINK, 40000, 0, PHASE_GROUND); + events.Repeat(Seconds(40)); break; case EVENT_BALCONY: events.SetPhase(PHASE_BALCONY); @@ -247,24 +247,24 @@ public: me->StopMoving(); me->RemoveAllAuras(); - events.ScheduleEvent(EVENT_BALCONY_TELEPORT, 3 * IN_MILLISECONDS, 0, PHASE_BALCONY); - events.ScheduleEvent(EVENT_WAVE, urand(5 * IN_MILLISECONDS, 8 * IN_MILLISECONDS), 0, PHASE_BALCONY); + events.ScheduleEvent(EVENT_BALCONY_TELEPORT, Seconds(3), 0, PHASE_BALCONY); + events.ScheduleEvent(EVENT_WAVE, randtime(Seconds(5), Seconds(8)), 0, PHASE_BALCONY); - uint8 secondsBalcony; + uint8 timeBalcony; switch (balconyCount) { case 0: - secondsBalcony = 70; + timeBalcony = 70; break; case 1: - secondsBalcony = 97; + timeBalcony = 97; break; case 2: default: - secondsBalcony = 120; + timeBalcony = 120; break; } - events.ScheduleEvent(EVENT_GROUND, secondsBalcony * IN_MILLISECONDS, 0, PHASE_BALCONY); + events.ScheduleEvent(EVENT_GROUND, Seconds(timeBalcony), 0, PHASE_BALCONY); break; case EVENT_BALCONY_TELEPORT: Talk(EMOTE_TELEPORT_1); @@ -287,7 +287,7 @@ public: CastSummon(0, RAID_MODE(5, 10), RAID_MODE(5, 10)); break; } - events.ScheduleEvent(EVENT_WAVE, urand(30, 45) * IN_MILLISECONDS, 0, PHASE_BALCONY); + events.Repeat(randtime(Seconds(30), Seconds(45))); break; case EVENT_GROUND: ++balconyCount; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp index b8ce402a939..cfa6e2e9f30 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp @@ -97,8 +97,8 @@ public: _EnterCombat(); Enraged = false; Talk(SAY_AGGRO); - events.ScheduleEvent(EVENT_HATEFUL, 1 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_BERSERK, 6 * MINUTE * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_HATEFUL, Seconds(1)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(6)); instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_MAKE_QUICK_WERK_OF_HIM_STARTING_EVENT); } @@ -167,17 +167,17 @@ public: if (thirdThreatTarget) me->getThreatManager().addThreat(thirdThreatTarget, HATEFUL_THREAT_AMT); // this will only ever be used in 25m - events.ScheduleEvent(EVENT_HATEFUL, 1 * IN_MILLISECONDS); + events.Repeat(Seconds(1)); break; } case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); Talk(EMOTE_BERSERK); - events.ScheduleEvent(EVENT_SLIME, 2 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_SLIME, Seconds(2)); break; case EVENT_SLIME: - DoCastVictim(SPELL_SLIME_BOLT, true); - events.ScheduleEvent(EVENT_SLIME, 2 * IN_MILLISECONDS); + DoCastAOE(SPELL_SLIME_BOLT, true); + events.Repeat(Seconds(2)); break; } } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp index 1d12f64a949..548f8086eb8 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp @@ -104,6 +104,9 @@ public: void JustDied(Unit* /*killer*/) override { + for (ObjectGuid summonGuid : summons) + if (Creature* summon = ObjectAccessor::GetCreature(*me, summonGuid)) + summon->RemoveCharmAuras(); Talk(SAY_DEATH); DoCastAOE(SPELL_HOPELESS, true); @@ -117,10 +120,10 @@ public: me->StopMoving(); summons.DoZoneInCombat(); Talk(SAY_AGGRO); - events.ScheduleEvent(EVENT_ATTACK, 7 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_STRIKE, 21 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_SHOUT, 16 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_KNIFE, 10 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_ATTACK, Seconds(7)); + events.ScheduleEvent(EVENT_STRIKE, Seconds(21)); + events.ScheduleEvent(EVENT_SHOUT, Seconds(16)); + events.ScheduleEvent(EVENT_KNIFE, Seconds(10)); } void UpdateAI(uint32 diff) override @@ -141,16 +144,16 @@ public: break; case EVENT_STRIKE: DoCastVictim(SPELL_UNBALANCING_STRIKE); - events.ScheduleEvent(EVENT_STRIKE, 6 * IN_MILLISECONDS); + events.Repeat(Seconds(6)); return; case EVENT_SHOUT: DoCastAOE(SPELL_DISRUPTING_SHOUT); - events.ScheduleEvent(EVENT_SHOUT, 16 * IN_MILLISECONDS); + events.Repeat(Seconds(16)); return; case EVENT_KNIFE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f)) DoCast(target, SPELL_JAGGED_KNIFE); - events.ScheduleEvent(EVENT_KNIFE, urandms(10,15)); + events.Repeat(randtime(Seconds(10), Seconds(15))); return; } } @@ -174,7 +177,10 @@ class npc_dk_understudy : public CreatureScript struct npc_dk_understudyAI : public ScriptedAI { - npc_dk_understudyAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), bloodStrikeTimer(0) { } + npc_dk_understudyAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), bloodStrikeTimer(0) + { + creature->LoadEquipment(1); + } void EnterCombat(Unit* /*who*/) override { diff --git a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp index 68b9e252150..0c9a236e196 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "GameObjectAI.h" #include "ScriptedCreature.h" +#include "SpellScript.h" #include "Player.h" #include "SpellInfo.h" #include "naxxramas.h" @@ -31,25 +33,24 @@ enum Yells enum Spells { - SPELL_FROST_AURA = 28531, - SPELL_CLEAVE = 19983, - SPELL_TAIL_SWEEP = 55697, - SPELL_SUMMON_BLIZZARD = 28560, - SPELL_LIFE_DRAIN = 28542, - SPELL_ICEBOLT = 28522, - SPELL_FROST_BREATH = 29318, - SPELL_FROST_EXPLOSION = 28524, - SPELL_FROST_MISSILE = 30101, - SPELL_BERSERK = 26662, - SPELL_DIES = 29357, - SPELL_CHILL = 28547, - SPELL_CHECK_RESISTS = 60539, + SPELL_FROST_AURA = 28531, + SPELL_CLEAVE = 19983, + SPELL_TAIL_SWEEP = 55697, + SPELL_SUMMON_BLIZZARD = 28560, + SPELL_LIFE_DRAIN = 28542, + SPELL_ICEBOLT = 28522, + SPELL_FROST_BREATH_ANTICHEAT = 29318, // damage effect ignoring LoS on the entrance platform to prevent cheese + SPELL_FROST_BREATH = 28524, // damage effect below sapphiron + SPELL_FROST_MISSILE = 30101, // visual only + SPELL_BERSERK = 26662, + SPELL_DIES = 29357, + SPELL_CHECK_RESISTS = 60539, + SPELL_SAPPHIRON_WING_BUFFET = 29328 }; enum Phases { - PHASE_NULL = 0, - PHASE_BIRTH, + PHASE_BIRTH = 1, PHASE_GROUND, PHASE_FLIGHT }; @@ -72,9 +73,15 @@ enum Events EVENT_CHECK_RESISTS }; +enum Actions +{ + ACTION_BIRTH = 1 +}; + enum Misc { NPC_BLIZZARD = 16474, + NPC_WING_BUFFET = 17025, GO_ICEBLOCK = 181247, // The Hundred Club @@ -92,77 +99,74 @@ class boss_sapphiron : public CreatureScript struct boss_sapphironAI : public BossAI { boss_sapphironAI(Creature* creature) : - BossAI(creature, BOSS_SAPPHIRON), _iceboltCount(0), _map(me->GetMap()) + BossAI(creature, BOSS_SAPPHIRON) { Initialize(); } void Initialize() { - _phase = PHASE_NULL; - + _delayedDrain = false; _canTheHundredClub = true; } void InitializeAI() override { + if (instance->GetBossState(BOSS_SAPPHIRON) == DONE) + return; + _canTheHundredClub = true; - float x, y, z; - me->GetPosition(x, y, z); - me->SummonGameObject(GO_BIRTH, x, y, z, 0, 0, 0, 0, 0, 0); - me->SetVisible(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - me->SetReactState(REACT_PASSIVE); + if (!instance->GetData(DATA_HAD_SAPPHIRON_BIRTH)) + { + me->SetVisible(false); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + me->SetReactState(REACT_PASSIVE); + } BossAI::InitializeAI(); } void Reset() override { - _Reset(); - - if (_phase == PHASE_FLIGHT) + if (events.IsInPhase(PHASE_FLIGHT)) { - ClearIceBlock(); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_ICEBOLT); me->SetReactState(REACT_AGGRESSIVE); if (me->IsHovering()) { me->HandleEmoteCommand(EMOTE_ONESHOT_LAND); me->SetHover(false); } - me->SetDisableGravity(false); } + _Reset(); Initialize(); } + void DamageTaken(Unit* /*who*/, uint32& damage) override + { + if (damage < me->GetHealth() || !events.IsInPhase(PHASE_FLIGHT)) + return; + damage = me->GetHealth()-1; // don't die during air phase + } + void EnterCombat(Unit* /*who*/) override { _EnterCombat(); me->CastSpell(me, SPELL_FROST_AURA, true); - DoCast(me, SPELL_CHECK_RESISTS); - events.ScheduleEvent(EVENT_CHECK_RESISTS, 30 * IN_MILLISECONDS); - events.ScheduleEvent(EVENT_BERSERK, 15 * MINUTE * IN_MILLISECONDS); - EnterPhaseGround(); + events.SetPhase(PHASE_GROUND); + events.ScheduleEvent(EVENT_CHECK_RESISTS, Seconds(0)); + events.ScheduleEvent(EVENT_BERSERK, Minutes(15)); + EnterPhaseGround(true); } void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch(spell->Id) { - case SPELL_ICEBOLT: - { - IceBlockMap::iterator itr = _iceblocks.find(target->GetGUID()); - if (itr != _iceblocks.end() && !itr->second) - { - if (GameObject* iceblock = me->SummonGameObject(GO_ICEBLOCK, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, 0, 0, 0, 0, 25)) - itr->second = iceblock->GetGUID(); - } - break; - } case SPELL_CHECK_RESISTS: if (target && target->GetResistance(SPELL_SCHOOL_FROST) > MAX_FROST_RESISTANCE) _canTheHundredClub = false; @@ -179,41 +183,37 @@ class boss_sapphiron : public CreatureScript void MovementInform(uint32 /*type*/, uint32 id) override { if (id == 1) - events.ScheduleEvent(EVENT_LIFTOFF, 0); + events.ScheduleEvent(EVENT_LIFTOFF, Seconds(0), 0, PHASE_FLIGHT); } void DoAction(int32 param) override { - if (param == DATA_SAPPHIRON_BIRTH) + if (param == ACTION_BIRTH) { - _phase = PHASE_BIRTH; - events.ScheduleEvent(EVENT_BIRTH, 23 * IN_MILLISECONDS); + events.SetPhase(PHASE_BIRTH); + events.ScheduleEvent(EVENT_BIRTH, Seconds(23)); } } - void EnterPhaseGround() + void EnterPhaseGround(bool initial) { - _phase = PHASE_GROUND; me->SetReactState(REACT_AGGRESSIVE); - events.SetPhase(PHASE_GROUND); - events.ScheduleEvent(EVENT_CLEAVE, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_TAIL, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_DRAIN, 24 * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_BLIZZARD, urand(5, 10) * IN_MILLISECONDS, 0, PHASE_GROUND); - events.ScheduleEvent(EVENT_FLIGHT, 45 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_CLEAVE, randtime(Seconds(5), Seconds(15)), 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_TAIL, randtime(Seconds(7), Seconds(10)), 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_BLIZZARD, randtime(Seconds(5), Seconds(10)), 0, PHASE_GROUND); + if (initial) + { + events.ScheduleEvent(EVENT_DRAIN, randtime(Seconds(22), Seconds(28))); + events.ScheduleEvent(EVENT_FLIGHT, Seconds(48) + Milliseconds(500), 0, PHASE_GROUND); + } + else + events.ScheduleEvent(EVENT_FLIGHT, Minutes(1), 0, PHASE_GROUND); } - void ClearIceBlock() + inline void CastDrain() { - for (IceBlockMap::const_iterator itr = _iceblocks.begin(); itr != _iceblocks.end(); ++itr) - { - if (Player* player = ObjectAccessor::GetPlayer(*me, itr->first)) - player->RemoveAura(SPELL_ICEBOLT); - - if (GameObject* go = ObjectAccessor::GetGameObject(*me, itr->second)) - go->Delete(); - } - _iceblocks.clear(); + DoCastAOE(SPELL_LIFE_DRAIN); + events.ScheduleEvent(EVENT_DRAIN, randtime(Seconds(22), Seconds(28))); } uint32 GetData(uint32 data) const override @@ -226,15 +226,12 @@ class boss_sapphiron : public CreatureScript void UpdateAI(uint32 diff) override { - if (!_phase) - return; - events.Update(diff); - if (_phase != PHASE_BIRTH && !UpdateVictim()) + if (!events.IsInPhase(PHASE_BIRTH) && !UpdateVictim()) return; - if (_phase == PHASE_GROUND) + if (events.IsInPhase(PHASE_GROUND)) { while (uint32 eventId = events.ExecuteEvent()) { @@ -242,7 +239,10 @@ class boss_sapphiron : public CreatureScript { case EVENT_CHECK_RESISTS: DoCast(me, SPELL_CHECK_RESISTS); - events.ScheduleEvent(EVENT_CHECK_RESISTS, 30 * IN_MILLISECONDS); + events.Repeat(Seconds(30)); + return; + case EVENT_GROUND: + EnterPhaseGround(false); return; case EVENT_BERSERK: Talk(EMOTE_ENRAGE); @@ -250,27 +250,26 @@ class boss_sapphiron : public CreatureScript return; case EVENT_CLEAVE: DoCastVictim(SPELL_CLEAVE); - events.ScheduleEvent(EVENT_CLEAVE, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_CLEAVE, randtime(Seconds(5), Seconds(15)), 0, PHASE_GROUND); return; case EVENT_TAIL: DoCastAOE(SPELL_TAIL_SWEEP); - events.ScheduleEvent(EVENT_TAIL, urand(5, 15) * IN_MILLISECONDS, 0, PHASE_GROUND); + events.ScheduleEvent(EVENT_TAIL, randtime(Seconds(7), Seconds(10)), 0, PHASE_GROUND); return; case EVENT_DRAIN: - DoCastAOE(SPELL_LIFE_DRAIN); - events.ScheduleEvent(EVENT_DRAIN, 24 * IN_MILLISECONDS, 0, PHASE_GROUND); + if (events.IsInPhase(PHASE_FLIGHT)) + _delayedDrain = true; + else + CastDrain(); return; case EVENT_BLIZZARD: - { - if (Creature* summon = DoSummon(NPC_BLIZZARD, me, 0.0f, urand(25, 30) * IN_MILLISECONDS, TEMPSUMMON_TIMED_DESPAWN)) - summon->GetMotionMaster()->MoveRandom(40); - events.ScheduleEvent(EVENT_BLIZZARD, RAID_MODE(20, 7) * IN_MILLISECONDS, 0, PHASE_GROUND); + DoCastAOE(SPELL_SUMMON_BLIZZARD); + events.ScheduleEvent(EVENT_BLIZZARD, RAID_MODE(Seconds(20), Seconds(7)), 0, PHASE_GROUND); break; - } case EVENT_FLIGHT: if (HealthAbovePct(10)) { - _phase = PHASE_FLIGHT; + _delayedDrain = false; events.SetPhase(PHASE_FLIGHT); me->SetReactState(REACT_PASSIVE); me->AttackStop(); @@ -293,61 +292,69 @@ class boss_sapphiron : public CreatureScript { case EVENT_CHECK_RESISTS: DoCast(me, SPELL_CHECK_RESISTS); - events.ScheduleEvent(EVENT_CHECK_RESISTS, 30 * IN_MILLISECONDS); + events.Repeat(Seconds(30)); return; case EVENT_LIFTOFF: + { Talk(EMOTE_AIR_PHASE); - me->SetDisableGravity(true); + if (Creature* buffet = DoSummon(NPC_WING_BUFFET, me, 0.0f, 0, TEMPSUMMON_MANUAL_DESPAWN)) + _buffet = buffet->GetGUID(); + me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); me->SetHover(true); - events.ScheduleEvent(EVENT_ICEBOLT, 1500); - _iceboltCount = RAID_MODE(2, 3); + events.ScheduleEvent(EVENT_ICEBOLT, Seconds(7), 0, PHASE_FLIGHT); + + _iceboltTargets.clear(); + std::list<Unit*> targets; + SelectTargetList(targets, RAID_MODE(2, 3), SELECT_TARGET_RANDOM, 200.0f, true); + for (Unit* target : targets) + if (target) + _iceboltTargets.push_back(target->GetGUID()); return; + } case EVENT_ICEBOLT: { - std::vector<Unit*> targets; - std::list<HostileReference*>::const_iterator i = me->getThreatManager().getThreatList().begin(); - for (; i != me->getThreatManager().getThreatList().end(); ++i) - if ((*i)->getTarget()->GetTypeId() == TYPEID_PLAYER && !(*i)->getTarget()->HasAura(SPELL_ICEBOLT)) - targets.push_back((*i)->getTarget()); - - if (targets.empty()) - _iceboltCount = 0; - else + if (_iceboltTargets.empty()) { - std::vector<Unit*>::const_iterator itr = targets.begin(); - advance(itr, rand32() % targets.size()); - _iceblocks.insert(std::make_pair((*itr)->GetGUID(), ObjectGuid::Empty)); - DoCast(*itr, SPELL_ICEBOLT); - --_iceboltCount; + events.ScheduleEvent(EVENT_BREATH, Seconds(2), 0, PHASE_FLIGHT); + return; } - - if (_iceboltCount) - events.ScheduleEvent(EVENT_ICEBOLT, 1 * IN_MILLISECONDS); + ObjectGuid target = _iceboltTargets.back(); + if (Player* pTarget = ObjectAccessor::GetPlayer(*me, target)) + if (pTarget->IsAlive()) + DoCast(pTarget, SPELL_ICEBOLT); + _iceboltTargets.pop_back(); + + if (_iceboltTargets.empty()) + events.ScheduleEvent(EVENT_BREATH, Seconds(2), 0, PHASE_FLIGHT); else - events.ScheduleEvent(EVENT_BREATH, 1 * IN_MILLISECONDS); + events.Repeat(Seconds(3)); return; } case EVENT_BREATH: { Talk(EMOTE_BREATH); DoCastAOE(SPELL_FROST_MISSILE); - events.ScheduleEvent(EVENT_EXPLOSION, 8 * IN_MILLISECONDS); + events.ScheduleEvent(EVENT_EXPLOSION, Seconds(8), 0, PHASE_FLIGHT); return; } case EVENT_EXPLOSION: - CastExplosion(); - ClearIceBlock(); - events.ScheduleEvent(EVENT_LAND, 3 * IN_MILLISECONDS); + DoCastAOE(SPELL_FROST_BREATH); + DoCastAOE(SPELL_FROST_BREATH_ANTICHEAT); + events.ScheduleEvent(EVENT_LAND, Seconds(3) + Milliseconds(500), 0, PHASE_FLIGHT); return; case EVENT_LAND: + if (_delayedDrain) + CastDrain(); + if (Creature* cBuffet = ObjectAccessor::GetCreature(*me, _buffet)) + { + cBuffet->DespawnOrUnsummon(1 * IN_MILLISECONDS); + _buffet.Clear(); + } me->HandleEmoteCommand(EMOTE_ONESHOT_LAND); Talk(EMOTE_GROUND_PHASE); me->SetHover(false); - me->SetDisableGravity(false); - events.ScheduleEvent(EVENT_GROUND, 1500); - return; - case EVENT_GROUND: - EnterPhaseGround(); + events.SetPhase(PHASE_GROUND); + events.ScheduleEvent(EVENT_GROUND, Seconds(3) + Milliseconds(500), 0, PHASE_GROUND); return; case EVENT_BIRTH: me->SetVisible(true); @@ -359,56 +366,261 @@ class boss_sapphiron : public CreatureScript } } - void CastExplosion() + private: + std::vector<ObjectGuid> _iceboltTargets; + ObjectGuid _buffet; + bool _delayedDrain; + bool _canTheHundredClub; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new boss_sapphironAI(creature); + } +}; + +class go_sapphiron_birth : public GameObjectScript +{ + public: + go_sapphiron_birth() : GameObjectScript("go_sapphiron_birth") { } + + struct go_sapphiron_birthAI : public GameObjectAI + { + go_sapphiron_birthAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + void OnStateChanged(uint32 state, Unit* who) override + { + if (state == GO_ACTIVATED) + { + if (who) + { + if (Creature* sapphiron = ObjectAccessor::GetCreature(*go, instance->GetGuidData(DATA_SAPPHIRON))) + sapphiron->AI()->DoAction(ACTION_BIRTH); + instance->SetData(DATA_HAD_SAPPHIRON_BIRTH, 1u); + } + } + else if (state == GO_JUST_DEACTIVATED) + { // prevent ourselves from going back to _READY and resetting the client anim + go->SetRespawnTime(0); + go->Delete(); + } + } + + InstanceScript* instance; + }; + + GameObjectAI* GetAI(GameObject* go) const override + { + return GetInstanceAI<go_sapphiron_birthAI>(go); + } +}; + + +class spell_sapphiron_change_blizzard_target : public SpellScriptLoader +{ + public: + spell_sapphiron_change_blizzard_target() : SpellScriptLoader("spell_sapphiron_change_blizzard_target") { } + + class spell_sapphiron_change_blizzard_target_AuraScript : public AuraScript + { + PrepareAuraScript(spell_sapphiron_change_blizzard_target_AuraScript); + + void HandlePeriodic(AuraEffect const* /*eff*/) + { + TempSummon* me = GetTarget()->ToTempSummon(); + if (Creature* owner = me ? me->GetSummonerCreatureBase() : nullptr) + { + Unit* newTarget = owner->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true); + if (!newTarget) + newTarget = owner->getAttackerForHelper(); + if (newTarget) + me->GetMotionMaster()->MoveFollow(newTarget, 0.1f, 0.0f); + else + { + me->StopMoving(); + me->GetMotionMaster()->Clear(); + } + } + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_sapphiron_change_blizzard_target_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_sapphiron_change_blizzard_target_AuraScript(); + } +}; + +class spell_sapphiron_icebolt : public SpellScriptLoader +{ + public: + spell_sapphiron_icebolt() : SpellScriptLoader("spell_sapphiron_icebolt") { } + + class spell_sapphiron_icebolt_AuraScript : public AuraScript + { + PrepareAuraScript(spell_sapphiron_icebolt_AuraScript); + + void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) + { + GetTarget()->ApplySpellImmune(SPELL_ICEBOLT, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_FROST, true); + } + + void HandleRemove(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) + { + if (_block) + if (GameObject* oBlock = ObjectAccessor::GetGameObject(*GetTarget(), _block)) + oBlock->Delete(); + GetTarget()->ApplySpellImmune(SPELL_ICEBOLT, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_FROST, false); + } + + void HandlePeriodic(AuraEffect const* /*eff*/) + { + if (_block) + return; + if (GetTarget()->isMoving()) + return; + float x, y, z; + GetTarget()->GetPosition(x, y, z); + if (GameObject* block = GetTarget()->SummonGameObject(GO_ICEBLOCK, x, y, z, 0.f, G3D::Quat(), 25)) + _block = block->GetGUID(); + } + + void Register() override + { + AfterEffectApply += AuraEffectApplyFn(spell_sapphiron_icebolt_AuraScript::HandleApply, EFFECT_0, SPELL_AURA_MOD_STUN, AURA_EFFECT_HANDLE_REAL); + AfterEffectRemove += AuraEffectRemoveFn(spell_sapphiron_icebolt_AuraScript::HandleRemove, EFFECT_0, SPELL_AURA_MOD_STUN, AURA_EFFECT_HANDLE_REAL); + OnEffectPeriodic += AuraEffectPeriodicFn(spell_sapphiron_icebolt_AuraScript::HandlePeriodic, EFFECT_2, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + } + + ObjectGuid _block; + }; + + AuraScript* GetAuraScript() const override + { + return new spell_sapphiron_icebolt_AuraScript(); + } +}; + +// @hack Hello, developer from the future! How has your day been? +// Anyway, this is, as you can undoubtedly see, a hack to emulate line of sight checks on a spell that abides line of sight anyway. +// In the current core, line of sight is not properly checked for people standing behind an ice block. This is not a good thing and kills people. +// Thus, we have this hack to check for ice block LoS in a "safe" way. Kind of. It's inaccurate, but in a good way (tends to save people when it shouldn't in edge cases). +// If LoS handling is better in whatever the current revision is when you read this, please get rid of the hack. Thanks! +class spell_sapphiron_frost_breath : public SpellScriptLoader +{ + public: + spell_sapphiron_frost_breath() : SpellScriptLoader("spell_sapphiron_frost_breath") { } + + class spell_sapphiron_frost_breath_SpellScript : public SpellScript + { + PrepareSpellScript(spell_sapphiron_frost_breath_SpellScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + return !!sSpellMgr->GetSpellInfo(SPELL_FROST_BREATH); + } + + void HandleTargets(std::list<WorldObject*>& targetList) { - DoZoneInCombat(); // make sure everyone is in threatlist - std::vector<Unit*> targets; - std::list<HostileReference*>::const_iterator i = me->getThreatManager().getThreatList().begin(); - for (; i != me->getThreatManager().getThreatList().end(); ++i) + std::list<GameObject*> blocks; + if (GetCaster()) + GetCaster()->GetGameObjectListWithEntryInGrid(blocks, GO_ICEBLOCK, 200.0f); + + std::vector<Unit*> toRemove; + toRemove.reserve(3); + std::list<WorldObject*>::iterator it = targetList.begin(); + while (it != targetList.end()) { - Unit* target = (*i)->getTarget(); - if (target->GetTypeId() != TYPEID_PLAYER) + Unit* target = (*it)->ToUnit(); + if (!target) + { + it = targetList.erase(it); continue; + } if (target->HasAura(SPELL_ICEBOLT)) { - target->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, true); - targets.push_back(target); + it = targetList.erase(it); + toRemove.push_back(target); + continue; + } + + bool found = false; + for (GameObject* block : blocks) + if (block->IsInBetween(GetCaster(), target, 2.0f) && GetCaster()->GetExactDist2d(block) + 5 >= GetCaster()->GetExactDist2d(target)) + { + found = true; + break; + } + if (found) + { + it = targetList.erase(it); continue; } + ++it; + } + + for (Unit* block : toRemove) + block->RemoveAura(SPELL_ICEBOLT); + } + + void Register() override + { + OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_sapphiron_frost_breath_SpellScript::HandleTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY); + } + }; - for (IceBlockMap::const_iterator itr = _iceblocks.begin(); itr != _iceblocks.end(); ++itr) + SpellScript* GetSpellScript() const override + { + return new spell_sapphiron_frost_breath_SpellScript(); + } +}; + +class spell_sapphiron_summon_blizzard : public SpellScriptLoader +{ + public: + spell_sapphiron_summon_blizzard() : SpellScriptLoader("spell_sapphiron_summon_blizzard") { } + + class spell_sapphiron_summon_blizzard_SpellScript : public SpellScript + { + PrepareSpellScript(spell_sapphiron_summon_blizzard_SpellScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + return !!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BLIZZARD); + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + if (Unit* target = GetHitUnit()) + if (Creature* blizzard = GetCaster()->SummonCreature(NPC_BLIZZARD, *target, TEMPSUMMON_TIMED_DESPAWN, urandms(25, 30))) { - if (GameObject* go = ObjectAccessor::GetGameObject(*me, itr->second)) + blizzard->CastSpell(nullptr, blizzard->m_spells[0], TRIGGERED_NONE); + if (Creature* creatureCaster = GetCaster()->ToCreature()) { - if (go->IsInBetween(me, target, 2.0f) - && me->GetExactDist2d(target->GetPositionX(), target->GetPositionY()) - me->GetExactDist2d(go->GetPositionX(), go->GetPositionY()) < 5.0f) + if (Unit* newTarget = creatureCaster->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true)) { - target->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, true); - targets.push_back(target); - break; + blizzard->GetMotionMaster()->MoveFollow(newTarget, 0.1f, 0.0f); + return; } } + blizzard->GetMotionMaster()->MoveFollow(target, 0.1f, 0.0f); } - } - - me->CastSpell(me, SPELL_FROST_EXPLOSION, true); - - for (std::vector<Unit*>::const_iterator itr = targets.begin(); itr != targets.end(); ++itr) - (*itr)->ApplySpellImmune(0, IMMUNITY_ID, SPELL_FROST_EXPLOSION, false); } - private: - Phases _phase; - uint32 _iceboltCount; - IceBlockMap _iceblocks; - bool _canTheHundredClub; - Map* _map; + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_sapphiron_summon_blizzard_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } }; - CreatureAI* GetAI(Creature* creature) const override + SpellScript* GetSpellScript() const override { - return new boss_sapphironAI(creature); + return new spell_sapphiron_summon_blizzard_SpellScript(); } }; @@ -426,5 +638,10 @@ class achievement_the_hundred_club : public AchievementCriteriaScript void AddSC_boss_sapphiron() { new boss_sapphiron(); + new go_sapphiron_birth(); + new spell_sapphiron_change_blizzard_target(); + new spell_sapphiron_icebolt(); + new spell_sapphiron_frost_breath(); + new spell_sapphiron_summon_blizzard(); new achievement_the_hundred_club(); } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp index 7330f90e585..2cf3a4664dd 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp @@ -109,6 +109,10 @@ enum PetSpells SPELL_MAGNETIC_PULL = 54517, SPELL_MAGNETIC_PULL_EFFECT = 28337, + // @hack feugen/stalagg use this in P1 after gripping tanks to prevent mmaps from pathing them off the platform once they approach the ramp + // developer from the future, if you read this and mmaps in the room has been fixed, then get rid of the hackfix, please + SPELL_ROOT_SELF = 75215, + SPELL_TESLA_SHOCK = 28099 }; @@ -166,10 +170,12 @@ public: struct boss_thaddiusAI : public BossAI { public: - boss_thaddiusAI(Creature* creature) : BossAI(creature, BOSS_THADDIUS), stalaggAlive(true), feugenAlive(true), ballLightningEnabled(false), shockingEligibility(true) + boss_thaddiusAI(Creature* creature) : BossAI(creature, BOSS_THADDIUS), stalaggAlive(true), feugenAlive(true), ballLightningUnlocked(false), ballLightningEnabled(false), shockingEligibility(true) {} + + void InitializeAI() override { if (instance->GetBossState(BOSS_THADDIUS) != DONE) - { + { events.SetPhase(PHASE_NOT_ENGAGED); SetCombatMovement(false); @@ -184,12 +190,33 @@ public: Talk(SAY_SLAY); } - void Reset() override + void Reset() override { } + + void EnterEvadeMode(EvadeReason why) override { + if (!ballLightningEnabled && why == EVADE_REASON_NO_HOSTILES) + { + ballLightningEnabled = true; + return; // try again + } if (events.IsInPhase(PHASE_TRANSITION) || (events.IsInPhase(PHASE_THADDIUS) && me->IsAlive())) BeginResetEncounter(); } + bool CanAIAttack(Unit const* who) const override + { + if (ballLightningEnabled || me->IsWithinMeleeRange(who)) + return BossAI::CanAIAttack(who); + else + return false; + } + + void JustRespawned() override + { + if (events.IsInPhase(PHASE_RESETTING)) + ResetEncounter(); + } + void JustDied(Unit* /*killer*/) override { _JustDied(); @@ -217,18 +244,25 @@ public: case ACTION_FEUGEN_AGGRO: case ACTION_STALAGG_AGGRO: if (events.IsInPhase(PHASE_RESETTING)) - return BeginResetEncounter(); + { + BeginResetEncounter(); + return; + } if (!events.IsInPhase(PHASE_NOT_ENGAGED)) return; events.SetPhase(PHASE_PETS); shockingEligibility = true; - + if (!instance->CheckRequiredBosses(BOSS_THADDIUS)) - return BeginResetEncounter(); + { + BeginResetEncounter(); + return; + } instance->SetBossState(BOSS_THADDIUS, IN_PROGRESS); me->setActive(true); + DoZoneInCombat(); if (Creature* stalagg = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_STALAGG))) stalagg->setActive(true); if (Creature* feugen = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FEUGEN))) @@ -239,7 +273,7 @@ public: feugen->AI()->DoAction(ACTION_FEUGEN_REVIVING_FX); feugenAlive = false; if (stalaggAlive) - events.ScheduleEvent(EVENT_REVIVE_FEUGEN, 5 * IN_MILLISECONDS, 0, PHASE_PETS); + events.ScheduleEvent(EVENT_REVIVE_FEUGEN, Seconds(5), 0, PHASE_PETS); else Transition(); @@ -249,7 +283,7 @@ public: stalagg->AI()->DoAction(ACTION_STALAGG_REVIVING_FX); stalaggAlive = false; if (feugenAlive) - events.ScheduleEvent(EVENT_REVIVE_STALAGG, 5 * IN_MILLISECONDS, 0, PHASE_PETS); + events.ScheduleEvent(EVENT_REVIVE_STALAGG, Seconds(5), 0, PHASE_PETS); else Transition(); @@ -274,9 +308,9 @@ public: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_TRANSITION_1, 10 * IN_MILLISECONDS, 0, PHASE_TRANSITION); - events.ScheduleEvent(EVENT_TRANSITION_2, 12 * IN_MILLISECONDS, 0, PHASE_TRANSITION); - events.ScheduleEvent(EVENT_TRANSITION_3, 14 * IN_MILLISECONDS, 0, PHASE_TRANSITION); + events.ScheduleEvent(EVENT_TRANSITION_1, Seconds(10), 0, PHASE_TRANSITION); + events.ScheduleEvent(EVENT_TRANSITION_2, Seconds(12), 0, PHASE_TRANSITION); + events.ScheduleEvent(EVENT_TRANSITION_3, Seconds(14), 0, PHASE_TRANSITION); } void BeginResetEncounter(bool initial = false) @@ -286,16 +320,12 @@ public: if (events.IsInPhase(PHASE_RESETTING)) return; - if (initial) // signal shorter spawn timer to instance script - instance->SetBossState(BOSS_THADDIUS, SPECIAL); - instance->ProcessEvent(me, EVENT_THADDIUS_BEGIN_RESET); - instance->SetBossState(BOSS_THADDIUS, NOT_STARTED); - // remove polarity shift debuffs on reset instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_POSITIVE_CHARGE_APPLY); instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_NEGATIVE_CHARGE_APPLY); me->DespawnOrUnsummon(); + me->SetRespawnTime(initial ? 5 : 30); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED); events.SetPhase(PHASE_RESETTING); @@ -312,11 +342,9 @@ public: feugenAlive = true; stalaggAlive = true; - me->Respawn(true); _Reset(); events.SetPhase(PHASE_NOT_ENGAGED); - - me->CastSpell(me, SPELL_THADDIUS_INACTIVE_VISUAL, true); + me->SetReactState(REACT_PASSIVE); if (Creature* feugen = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FEUGEN))) feugen->AI()->DoAction(ACTION_RESET_ENCOUNTER); @@ -361,16 +389,20 @@ public: break; case EVENT_TRANSITION_3: // thaddius becomes active me->CastSpell(me, SPELL_THADDIUS_SPARK_VISUAL, true); - ballLightningEnabled = false; + ballLightningUnlocked = false; me->RemoveAura(SPELL_THADDIUS_INACTIVE_VISUAL); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); - + me->SetReactState(REACT_AGGRESSIVE); + DoZoneInCombat(); if (Unit* closest = SelectTarget(SELECT_TARGET_NEAREST, 0, 500.0f)) AttackStart(closest); else // if there is no nearest target, then there is no target, meaning we should reset - return BeginResetEncounter(); + { + BeginResetEncounter(); + return; + } if (Creature* feugen = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FEUGEN))) feugen->AI()->DoAction(ACTION_TRANSITION_3); @@ -381,20 +413,20 @@ public: Talk(SAY_AGGRO); - events.ScheduleEvent(EVENT_ENABLE_BALL_LIGHTNING, 5 * IN_MILLISECONDS, 0, PHASE_THADDIUS); - events.ScheduleEvent(EVENT_SHIFT, 10 * IN_MILLISECONDS, 0, PHASE_THADDIUS); - events.ScheduleEvent(EVENT_CHAIN, urand(10, 20) * IN_MILLISECONDS, 0, PHASE_THADDIUS); - events.ScheduleEvent(EVENT_BERSERK, 6 * MINUTE * IN_MILLISECONDS, 0, PHASE_THADDIUS); + events.ScheduleEvent(EVENT_ENABLE_BALL_LIGHTNING, Seconds(5), 0, PHASE_THADDIUS); + events.ScheduleEvent(EVENT_SHIFT, Seconds(10), 0, PHASE_THADDIUS); + events.ScheduleEvent(EVENT_CHAIN, randtime(Seconds(10), Seconds(20)), 0, PHASE_THADDIUS); + events.ScheduleEvent(EVENT_BERSERK, Minutes(6), 0, PHASE_THADDIUS); break; case EVENT_ENABLE_BALL_LIGHTNING: - ballLightningEnabled = true; + ballLightningUnlocked = true; break; case EVENT_SHIFT: me->CastStop(); // shift overrides all other spells DoCastAOE(SPELL_POLARITY_SHIFT); - events.ScheduleEvent(EVENT_SHIFT_TALK, 3 * IN_MILLISECONDS, PHASE_THADDIUS); - events.ScheduleEvent(EVENT_SHIFT, 30 * IN_MILLISECONDS, PHASE_THADDIUS); + events.ScheduleEvent(EVENT_SHIFT_TALK, Seconds(3), PHASE_THADDIUS); + events.ScheduleEvent(EVENT_SHIFT, Seconds(30), PHASE_THADDIUS); break; case EVENT_SHIFT_TALK: Talk(SAY_ELECT); @@ -402,12 +434,12 @@ public: break; case EVENT_CHAIN: if (me->FindCurrentSpellBySpellId(SPELL_POLARITY_SHIFT)) // delay until shift is over - events.ScheduleEvent(EVENT_CHAIN, 3 * IN_MILLISECONDS, 0, PHASE_THADDIUS); + events.Repeat(Seconds(3)); else { me->CastStop(); DoCastVictim(SPELL_CHAIN_LIGHTNING); - events.ScheduleEvent(EVENT_CHAIN, urand(10, 20) * IN_MILLISECONDS, PHASE_THADDIUS); + events.Repeat(randtime(Seconds(10), Seconds(20))); } break; case EVENT_BERSERK: @@ -418,22 +450,24 @@ public: break; } } - - if (events.IsInPhase(PHASE_THADDIUS)) + if (events.IsInPhase(PHASE_THADDIUS) && !me->HasUnitState(UNIT_STATE_CASTING) && me->isAttackReady()) { if (me->IsWithinMeleeRange(me->GetVictim())) + { + ballLightningEnabled = false; DoMeleeAttackIfReady(); - else - if (ballLightningEnabled) - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) - DoCast(target, SPELL_BALL_LIGHTNING); + } + else if (ballLightningUnlocked) + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) + DoCast(target, SPELL_BALL_LIGHTNING); } } private: bool stalaggAlive; bool feugenAlive; - bool ballLightningEnabled; + bool ballLightningUnlocked; // whether the initial ball lightning grace period has expired and we should proceed to exterminate with extreme prejudice + bool ballLightningEnabled; // switch that is flipped to true if we try to evade due to no eligible targets in melee range bool shockingEligibility; }; @@ -521,7 +555,7 @@ public: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Talk(EMOTE_FEIGN_REVIVE); isFeignDeath = false; - + refreshBeam = true; // force beam refresh if (Creature* feugen = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FEUGEN))) @@ -586,7 +620,7 @@ public: damage = 0; return; } - + isFeignDeath = true; isOverloading = false; @@ -652,7 +686,7 @@ public: else { DoCast(me, SPELL_STALAGG_POWERSURGE); - powerSurgeTimer = urand(25, 30) * IN_MILLISECONDS; + powerSurgeTimer = urandms(25, 30); } } else @@ -790,7 +824,7 @@ public: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Talk(EMOTE_FEIGN_REVIVE); isFeignDeath = false; - + refreshBeam = true; // force beam refresh if (Creature* stalagg = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_STALAGG))) @@ -836,7 +870,7 @@ public: Talk(SAY_FEUGEN_AGGRO); if (Creature* thaddius = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THADDIUS))) - thaddius->AI()->DoAction(ACTION_STALAGG_AGGRO); + thaddius->AI()->DoAction(ACTION_FEUGEN_AGGRO); if (Creature* stalagg = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_STALAGG))) if (!stalagg->IsInCombat()) @@ -922,7 +956,7 @@ public: magneticPullTimer = 20 * IN_MILLISECONDS; } else magneticPullTimer -= uiDiff; - + if (staticFieldTimer <= uiDiff) { DoCast(me, SPELL_FEUGEN_STATICFIELD); @@ -971,7 +1005,7 @@ public: ObjectGuid _myCoil; ObjectGuid _myCoilGO; - + bool isOverloading; bool refreshBeam; bool isFeignDeath; @@ -1094,7 +1128,7 @@ class spell_thaddius_polarity_charge : public SpellScriptLoader SpellScript* GetSpellScript() const override { - return new spell_thaddius_polarity_charge_SpellScript; + return new spell_thaddius_polarity_charge_SpellScript(); } }; @@ -1169,7 +1203,7 @@ class spell_thaddius_magnetic_pull : public SpellScriptLoader Unit* feugen = GetCaster(); if (!feugen || feugen->GetEntry() != NPC_FEUGEN) return; - + Unit* stalagg = ObjectAccessor::GetCreature(*feugen, feugen->GetInstanceScript()->GetGuidData(DATA_STALAGG)); if (!stalagg) return; @@ -1212,6 +1246,10 @@ class spell_thaddius_magnetic_pull : public SpellScriptLoader feugenTank->CastSpell(stalaggTank, SPELL_MAGNETIC_PULL_EFFECT, true); stalaggTank->CastSpell(feugenTank, SPELL_MAGNETIC_PULL_EFFECT, true); + // @hack prevent mmaps clusterfucks from breaking tesla while tanks are midair + feugen->AddAura(SPELL_ROOT_SELF, feugen); + stalagg->AddAura(SPELL_ROOT_SELF, stalagg); + // and make both attack their respective new tanks if (feugen->GetAI()) feugen->GetAI()->AttackStart(stalaggTank); diff --git a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp index c8a4eb7fbc8..720549de0b2 100644 --- a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp +++ b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp @@ -20,7 +20,7 @@ #include "InstanceScript.h" #include "naxxramas.h" -BossBoundaryData const boundaries = +BossBoundaryData const boundaries = { /* Arachnid Quarter */ { BOSS_ANUBREKHAN, new CircleBoundary(Position(3273.376709f, -3475.876709f), Position(3195.668213f, -3475.930176f)) }, @@ -100,36 +100,6 @@ ObjectData const objectData[] = { 0, 0, } }; -// from P2 teleport spell stored target -float const HeiganPos[2] = { 2793.86f, -3707.38f }; -float const HeiganEruptionSlope[3] = -{ - (-3703.303223f - HeiganPos[1]) / (2777.494141f - HeiganPos[0]), // between right center and far right - (-3696.948242f - HeiganPos[1]) / (2785.624268f - HeiganPos[0]), // between left and right halves - (-3691.880615f - HeiganPos[1]) / (2790.280029f - HeiganPos[0]) // between far left and left center -}; - -// 0 H x -// 1 ^ -// 2 | -// 3 y<--o -inline uint32 GetEruptionSection(float x, float y) -{ - y -= HeiganPos[1]; - if (y < 1.0f) - return 0; - - x -= HeiganPos[0]; - if (x > -1.0f) - return 3; - - float slope = y/x; - for (uint32 i = 0; i < 3; ++i) - if (slope > HeiganEruptionSlope[i]) - return i; - return 3; -} - class instance_naxxramas : public InstanceMapScript { public: @@ -149,9 +119,13 @@ class instance_naxxramas : public InstanceMapScript hadAnubRekhanGreet = false; hadFaerlinaGreet = false; hadThaddiusGreet = false; + hadSapphironBirth = false; CurrentWingTaunt = SAY_KELTHUZAD_FIRST_WING_TAUNT; playerDied = 0; + + nextFroggerWave = 0; + events.ScheduleEvent(EVENT_SUMMON_FROGGER_WAVE, Seconds(1)); } void OnCreatureCreate(Creature* creature) override @@ -182,6 +156,9 @@ class instance_naxxramas : public InstanceMapScript case NPC_SIR: SirGUID = creature->GetGUID(); break; + case NPC_GLUTH: + GluthGUID = creature->GetGUID(); + break; case NPC_HEIGAN: HeiganGUID = creature->GetGUID(); break; @@ -208,28 +185,8 @@ class instance_naxxramas : public InstanceMapScript } } - void ProcessEvent(WorldObject* /*source*/, uint32 eventId) override - { - switch (eventId) - { - case EVENT_THADDIUS_BEGIN_RESET: - if (GetBossState(BOSS_THADDIUS) == SPECIAL) // this is the initial spawn, we want a shorter spawn time - events.ScheduleEvent(EVENT_THADDIUS_RESET, 5 * IN_MILLISECONDS); - else - events.ScheduleEvent(EVENT_THADDIUS_RESET, 30 * IN_MILLISECONDS); - break; - } - } - void OnGameObjectCreate(GameObject* go) override { - if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287) - { - uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY()); - HeiganEruptionGUID[section].insert(go->GetGUID()); - return; - } - switch (go->GetEntry()) { case GO_GOTHIK_GATE: @@ -273,37 +230,18 @@ class instance_naxxramas : public InstanceMapScript if (GetBossState(BOSS_HORSEMEN) == DONE) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); break; - default: - break; - } - - InstanceScript::OnGameObjectCreate(go); - } - - void OnGameObjectRemove(GameObject* go) override - { - if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287) - { - uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY()); - HeiganEruptionGUID[section].erase(go->GetGUID()); - return; - } - - switch (go->GetEntry()) - { case GO_BIRTH: - if (SapphironGUID) + if (hadSapphironBirth || GetBossState(BOSS_SAPPHIRON) == DONE) { - if (Creature* sapphiron = instance->GetCreature(SapphironGUID)) - sapphiron->AI()->DoAction(DATA_SAPPHIRON_BIRTH); - return; + hadSapphironBirth = true; + go->Delete(); } break; default: break; } - InstanceScript::OnGameObjectRemove(go); + InstanceScript::OnGameObjectCreate(go); } void OnUnitDeath(Unit* unit) override @@ -328,9 +266,6 @@ class instance_naxxramas : public InstanceMapScript { switch (id) { - case DATA_HEIGAN_ERUPT: - HeiganErupt(value); - break; case DATA_GOTHIK_GATE: if (GameObject* gate = instance->GetGameObject(GothikGateGUID)) gate->SetGoState(GOState(value)); @@ -347,6 +282,9 @@ class instance_naxxramas : public InstanceMapScript case DATA_HAD_THADDIUS_GREET: hadThaddiusGreet = (value == 1u); break; + case DATA_HAD_SAPPHIRON_BIRTH: + hadSapphironBirth = (value == 1u); + break; default: break; } @@ -364,6 +302,8 @@ class instance_naxxramas : public InstanceMapScript return hadFaerlinaGreet ? 1u : 0u; case DATA_HAD_THADDIUS_GREET: return hadThaddiusGreet ? 1u : 0u; + case DATA_HAD_SAPPHIRON_BIRTH: + return hadSapphironBirth ? 1u : 0u; default: break; } @@ -393,12 +333,16 @@ class instance_naxxramas : public InstanceMapScript return SirGUID; case DATA_HEIGAN: return HeiganGUID; + case DATA_GLUTH: + return GluthGUID; case DATA_FEUGEN: return FeugenGUID; case DATA_STALAGG: return StalaggGUID; case DATA_THADDIUS: return ThaddiusGUID; + case DATA_SAPPHIRON: + return SapphironGUID; case DATA_KELTHUZAD: return KelthuzadGUID; case DATA_KELTHUZAD_PORTAL01: @@ -431,7 +375,7 @@ class instance_naxxramas : public InstanceMapScript if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_ARACHNID)) teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000); + events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, Seconds(6)); } break; case BOSS_LOATHEB: @@ -440,7 +384,7 @@ class instance_naxxramas : public InstanceMapScript if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_PLAGUE)) teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000); + events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, Seconds(6)); } break; case BOSS_THADDIUS: @@ -449,12 +393,12 @@ class instance_naxxramas : public InstanceMapScript if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_CONSTRUCT)) teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000); + events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, Seconds(6)); } break; case BOSS_GOTHIK: if (state == DONE) - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ, 10000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ, Seconds(10)); break; case BOSS_HORSEMEN: if (state == DONE) @@ -468,12 +412,12 @@ class instance_naxxramas : public InstanceMapScript if (GameObject* teleporter = GetGameObject(DATA_NAXX_PORTAL_MILITARY)) teleporter->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, 6000); + events.ScheduleEvent(EVENT_KELTHUZAD_WING_TAUNT, Seconds(6)); } break; case BOSS_SAPPHIRON: if (state == DONE) - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD, Seconds(6)); break; default: break; @@ -493,37 +437,37 @@ class instance_naxxramas : public InstanceMapScript case EVENT_DIALOGUE_GOTHIK_KORTHAZZ: if (Creature* korthazz = instance->GetCreature(ThaneGUID)) korthazz->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK, 5000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK, Seconds(5)); break; case EVENT_DIALOGUE_GOTHIK_ZELIEK: if (Creature* zeliek = instance->GetCreature(SirGUID)) zeliek->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_BLAUMEUX: if (Creature* blaumeux = instance->GetCreature(LadyGUID)) blaumeux->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_RIVENDARE: if (Creature* rivendare = instance->GetCreature(BaronGUID)) rivendare->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX2, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_BLAUMEUX2, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_BLAUMEUX2: if (Creature* blaumeux = instance->GetCreature(LadyGUID)) blaumeux->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK2, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_ZELIEK2, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_ZELIEK2: if (Creature* zeliek = instance->GetCreature(SirGUID)) zeliek->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ2, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_KORTHAZZ2, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_KORTHAZZ2: if (Creature* korthazz = instance->GetCreature(ThaneGUID)) korthazz->AI()->Talk(SAY_DIALOGUE_GOTHIK_HORSEMAN2); - events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE2, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_GOTHIK_RIVENDARE2, Seconds(6)); break; case EVENT_DIALOGUE_GOTHIK_RIVENDARE2: if (Creature* rivendare = instance->GetCreature(BaronGUID)) @@ -536,66 +480,53 @@ class instance_naxxramas : public InstanceMapScript kelthuzad->AI()->Talk(CurrentWingTaunt); ++CurrentWingTaunt; break; + case EVENT_SUMMON_FROGGER_WAVE: + { + std::list<TempSummon*> spawns; + instance->SummonCreatureGroup(nextFroggerWave, &spawns); + if (!spawns.empty()) + (*spawns.begin())->GetMotionMaster()->MovePath(10 * NPC_FROGGER + nextFroggerWave, false); + events.Repeat(Seconds(1) + Milliseconds(666)); + nextFroggerWave = (nextFroggerWave+1) % 3; + break; + } case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD: if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID)) kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD); HandleGameObject(KelthuzadDoorGUID, false); - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING, Seconds(6)); break; case EVENT_DIALOGUE_SAPPHIRON_LICHKING: if (Creature* lichKing = instance->GetCreature(LichKingGUID)) lichKing->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_LICH_KING); - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD2, 16000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD2, Seconds(16)); break; case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD2: if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID)) kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD2); - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING2, 9000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_LICHKING2, Seconds(9)); break; case EVENT_DIALOGUE_SAPPHIRON_LICHKING2: if (Creature* lichKing = instance->GetCreature(LichKingGUID)) lichKing->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_LICH_KING2); - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD3, 12000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD3, Seconds(12)); break; case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD3: if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID)) kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD3); - events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD4, 6000); + events.ScheduleEvent(EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD4, Seconds(6)); break; case EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD4: if (Creature* kelthuzad = instance->GetCreature(KelthuzadGUID)) kelthuzad->AI()->Talk(SAY_DIALOGUE_SAPPHIRON_KELTHUZAD4); HandleGameObject(KelthuzadDoorGUID, true); break; - case EVENT_THADDIUS_RESET: - if (GetBossState(BOSS_THADDIUS) != DONE) - if (Creature* thaddius = instance->GetCreature(ThaddiusGUID)) - thaddius->AI()->DoAction(-1); - break; default: break; } } } - void HeiganErupt(uint32 section) - { - for (uint32 i = 0; i < 4; ++i) - { - if (i == section) - continue; - - for (ObjectGuid guid : HeiganEruptionGUID[i]) - { - if (GameObject* heiganEruption = instance->GetGameObject(guid)) - { - heiganEruption->SendCustomAnim(heiganEruption->GetGoAnimProgress()); - heiganEruption->CastSpell(NULL, SPELL_ERUPTION); - } - } - } - } - // This Function is called in CheckAchievementCriteriaMeet and CheckAchievementCriteriaMeet is called before SetBossState(bossId, DONE), // so to check if all bosses are done the checker must exclude 1 boss, the last done, if there is at most 1 encouter in progress when is // called this function then all bosses are done. The one boss that check is the boss that calls this function, so it is dead. @@ -653,7 +584,6 @@ class instance_naxxramas : public InstanceMapScript /* The Plague Quarter */ // Heigan the Unclean - GuidSet HeiganEruptionGUID[4]; ObjectGuid HeiganGUID; /* The Military Quarter */ @@ -670,6 +600,8 @@ class instance_naxxramas : public InstanceMapScript ObjectGuid HorsemenChestGUID; /* The Construct Quarter */ + // Gluth + ObjectGuid GluthGUID; // Thaddius ObjectGuid ThaddiusGUID; ObjectGuid FeugenGUID; @@ -688,11 +620,14 @@ class instance_naxxramas : public InstanceMapScript bool hadAnubRekhanGreet; bool hadFaerlinaGreet; bool hadThaddiusGreet; + bool hadSapphironBirth; uint8 CurrentWingTaunt; /* The Immortal / The Undying */ uint32 playerDied; + int8 nextFroggerWave; + EventMap events; }; diff --git a/src/server/scripts/Northrend/Naxxramas/naxxramas.h b/src/server/scripts/Northrend/Naxxramas/naxxramas.h index c0caa86e93f..75e7314c5d0 100644 --- a/src/server/scripts/Northrend/Naxxramas/naxxramas.h +++ b/src/server/scripts/Northrend/Naxxramas/naxxramas.h @@ -43,12 +43,11 @@ enum Encounter enum Data { - DATA_HEIGAN_ERUPT, DATA_GOTHIK_GATE, - DATA_SAPPHIRON_BIRTH, DATA_HAD_ANUBREKHAN_GREET, DATA_HAD_FAERLINA_GREET, DATA_HAD_THADDIUS_GREET, + DATA_HAD_SAPPHIRON_BIRTH, DATA_HORSEMEN_CHECK_ACHIEVEMENT_CREDIT, DATA_ABOMINATION_KILLED, @@ -69,10 +68,12 @@ enum Data64 DATA_LADY, DATA_BARON, DATA_SIR, + DATA_GLUTH, DATA_THADDIUS, DATA_HEIGAN, DATA_FEUGEN, DATA_STALAGG, + DATA_SAPPHIRON, DATA_KELTHUZAD, DATA_KELTHUZAD_PORTAL01, DATA_KELTHUZAD_PORTAL02, @@ -92,6 +93,7 @@ enum CreaturesIds NPC_LADY = 16065, NPC_BARON = 30549, NPC_SIR = 16063, + NPC_GLUTH = 15932, NPC_HEIGAN = 15936, NPC_THADDIUS = 15928, NPC_FEUGEN = 15930, @@ -105,7 +107,8 @@ enum CreaturesIds NPC_DK_UNDERSTUDY = 16803, NPC_BIGGLESWORTH = 16998, NPC_LICH_KING = 16980, - NPC_OLD_WORLD_TRIGGER = 15384 + NPC_OLD_WORLD_TRIGGER = 15384, + NPC_FROGGER = 16027 }; enum GameObjectsIds @@ -158,12 +161,6 @@ enum GameObjectsIds GO_NAXX_PORTAL_MILITARY = 181578 }; -enum SpellIds -{ - SPELL_ERUPTION = 29371, - SPELL_SLIME = 28801 -}; - enum InstanceEvents { // Dialogue that happens after Gothik's death. @@ -176,13 +173,12 @@ enum InstanceEvents EVENT_DIALOGUE_GOTHIK_KORTHAZZ2, EVENT_DIALOGUE_GOTHIK_RIVENDARE2, - // Thaddius AI requesting timed encounter (re-)spawn - EVENT_THADDIUS_BEGIN_RESET, - EVENT_THADDIUS_RESET, - // Dialogue that happens after each wing. EVENT_KELTHUZAD_WING_TAUNT, + // Periodic Frogger summon + EVENT_SUMMON_FROGGER_WAVE, + // Dialogue that happens after Sapphiron's death. EVENT_DIALOGUE_SAPPHIRON_KELTHUZAD, EVENT_DIALOGUE_SAPPHIRON_LICHKING, diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp index 277ca793a8f..914a1a8bbb0 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp @@ -376,8 +376,10 @@ public: me->SetDisableGravity(true); me->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND | UNIT_BYTE1_FLAG_HOVER); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); // TO DO: find what in core is making boss slower than in retail (when correct speed data) or find missing movement flag update or forced spline change - me->SetSpeed(MOVE_FLIGHT, _flySpeed * 0.25f); + me->SetSpeedRate(MOVE_FLIGHT, _flySpeed * 0.25f); if (_despawned) DoAction(ACTION_HANDLE_RESPAWN); @@ -464,7 +466,7 @@ public: pos.m_positionZ = alexstraszaBunny->GetPositionZ(); alexstraszaBunny->GetNearPoint2D(pos.m_positionX, pos.m_positionY, 30.0f, alexstraszaBunny->GetAngle(me)); me->GetMotionMaster()->MoveLand(POINT_LAND_P_ONE, pos); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); me->SetReactState(REACT_AGGRESSIVE); me->SetInCombatWithZone(); events.ScheduleEvent(EVENT_LAND_START_ENCOUNTER, 7*IN_MILLISECONDS, 1, PHASE_NOT_STARTED); @@ -603,9 +605,7 @@ public: me->SetRespawnDelay(respawnDelay); // Set speed to normal value - me->SetSpeed(MOVE_FLIGHT, _flySpeed); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + me->SetSpeedRate(MOVE_FLIGHT, _flySpeed); me->RemoveAllAuras(); me->CombatStop(); // Sometimes threat can remain, so it's a safety measure @@ -1001,14 +1001,7 @@ public: _JustDied(); Talk(SAY_DEATH); if (Creature* alexstraszaGiftBoxBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_GIFT_BOX_BUNNY_GUID))) - { - if (GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL) - alexstraszaGiftBoxBunny->SummonGameObject(GO_HEART_OF_MAGIC_10, HeartOfMagicSpawnPos.GetPositionX(), HeartOfMagicSpawnPos.GetPositionY(), - HeartOfMagicSpawnPos.GetPositionZ(), HeartOfMagicSpawnPos.GetOrientation(), 0.0f, 0.0f, 0.0f, 1.0f, 0); - else if (GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) - alexstraszaGiftBoxBunny->SummonGameObject(GO_HEART_OF_MAGIC_25, HeartOfMagicSpawnPos.GetPositionX(), HeartOfMagicSpawnPos.GetPositionY(), - HeartOfMagicSpawnPos.GetPositionZ(), HeartOfMagicSpawnPos.GetOrientation(), 0.0f, 0.0f, 0.0f, 1.0f, 0); - } + alexstraszaGiftBoxBunny->SummonGameObject(RAID_MODE(GO_HEART_OF_MAGIC_10, GO_HEART_OF_MAGIC_25), HeartOfMagicSpawnPos, G3D::Quat(), 0); me->SummonCreature(NPC_ALEXSTRASZA, AlexstraszaSpawnPos, TEMPSUMMON_MANUAL_DESPAWN); me->DespawnOrUnsummon(5*IN_MILLISECONDS); @@ -1165,7 +1158,7 @@ public: _instance = creature->GetInstanceScript(); me->SetReactState(REACT_PASSIVE); // TO DO: These were a bit faster than what they should be. Not sure what is the reason. - me->SetSpeed(MOVE_FLIGHT, 1.25f); + me->SetSpeedRate(MOVE_FLIGHT, 1.25f); } void Initialize() @@ -1224,13 +1217,15 @@ public: void DoAction(int32 /*action*/) override { if (Vehicle* vehicleTemp = me->GetVehicleKit()) + { if (vehicleTemp->GetPassenger(0) && vehicleTemp->GetPassenger(0)->GetTypeId() == TYPEID_PLAYER) { vehicleTemp->RemoveAllPassengers(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } + } - me->DespawnOrUnsummon(3*IN_MILLISECONDS); + me->DespawnOrUnsummon(3*IN_MILLISECONDS); } void MovementInform(uint32 type, uint32 id) override @@ -1274,7 +1269,7 @@ public: me->SetReactState(REACT_PASSIVE); // TO DO: Something is wrong with calculations for flying creatures that are on WP/Cyclic path. // They should get the same difference as to when at ground from run creature switch to walk. - me->SetSpeed(MOVE_FLIGHT, 0.45f); + me->SetSpeedRate(MOVE_FLIGHT, 0.45f); } void Reset() override @@ -1566,7 +1561,7 @@ public: { me->DespawnOrUnsummon(2050); me->SetOrientation(2.5f); - me->SetSpeed(MOVE_FLIGHT, 1.0f, true); + me->SetSpeedRate(MOVE_FLIGHT, 1.0f); Position pos = me->GetPosition(); pos.m_positionX += 10.0f; pos.m_positionY += 10.0f; @@ -2437,9 +2432,9 @@ class spell_alexstrasza_gift_beam_visual : public SpellScriptLoader if (Creature* target = GetTarget()->ToCreature()) { if (target->GetMap()->GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL) - _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_10, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_10, *target, G3D::Quat(), 0); else if (target->GetMap()->GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) - _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, *target, G3D::Quat(), 0); } } diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp b/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp index e87115dd8e2..eb8a92f7b28 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp @@ -86,9 +86,7 @@ public: void SpawnGameObject(uint32 entry, Position const& pos) { GameObject* go = new GameObject(); - if (!go->Create(instance->GenerateLowGuid<HighGuid::GameObject>(), entry, instance, - PHASEMASK_NORMAL, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), - 0, 0, 0, 0, 120, GO_STATE_READY)) + if (!go->Create(instance->GenerateLowGuid<HighGuid::GameObject>(), entry, instance, PHASEMASK_NORMAL, pos, G3D::Quat(), 255, GO_STATE_READY)) { delete go; return; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp index e1a4a6ed7b8..3d9ea97b136 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp @@ -375,7 +375,7 @@ class npc_ruby_emerald_amber_drake : public CreatureScript { me->DespawnOrUnsummon(2050); me->SetOrientation(2.5f); - me->SetSpeed(MOVE_FLIGHT, 1.0f, true); + me->SetSpeedRate(MOVE_FLIGHT, 1.0f); Talk(SAY_DRAKES_TAKEOFF); Position pos = me->GetPosition(); Position offset = { 10.0f, 10.0f, 12.0f, 0.0f }; diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp index a98da2c6e3d..55295a534e1 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp @@ -113,7 +113,7 @@ public: Initialize(); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_REMOVE_CLIENT_CONTROL); if (!me->IsVisible()) me->SetVisible(true); @@ -152,7 +152,7 @@ public: me->AttackStop(); me->SetVisible(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveIdle(); @@ -174,7 +174,7 @@ public: { if (pSpark->IsAlive()) { - pSpark->SetSpeed(MOVE_RUN, 2.0f); + pSpark->SetSpeedRate(MOVE_RUN, 2.0f); pSpark->GetMotionMaster()->Clear(); pSpark->GetMotionMaster()->MovePoint(DATA_POINT_CALLBACK, pos); } @@ -236,7 +236,7 @@ public: else if (lSparkList.empty()) { me->SetVisible(true); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_DISABLE_MOVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE|UNIT_FLAG_NOT_SELECTABLE|UNIT_FLAG_REMOVE_CLIENT_CONTROL); DoCast(me, SPELL_SPARK_DESPAWN, false); @@ -355,7 +355,7 @@ public: { Position pos = ionar->GetPosition(); - me->SetSpeed(MOVE_RUN, 2.0f); + me->SetSpeedRate(MOVE_RUN, 2.0f); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(DATA_POINT_CALLBACK, pos); } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp index 89868fc7bf2..b2a1bb70077 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp @@ -1164,6 +1164,7 @@ class spell_algalon_trigger_3_adds : public SpellScriptLoader void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_algalon_trigger_3_adds_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); + OnEffectHitTarget += SpellEffectFn(spell_algalon_trigger_3_adds_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp index 6dfc3bf01e7..98827fb3e00 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp @@ -334,7 +334,8 @@ class boss_flame_leviathan : public CreatureScript void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_START_THE_ENGINE) - ASSERT_NOTNULL(me->GetVehicleKit())->InstallAllAccessories(false); + if (Vehicle* vehicleKit = me->GetVehicleKit()) + vehicleKit->InstallAllAccessories(false); if (spell->Id == SPELL_ELECTROSHOCK) me->InterruptSpell(CURRENT_CHANNELED_SPELL); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp index 05beacca638..fa59c021cad 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp @@ -171,8 +171,7 @@ enum FreyaNpcs enum FreyaActions { - ACTION_ELDER_DEATH = 1, - ACTION_ELDER_FREYA_KILLED = 2 + ACTION_ELDER_FREYA_KILLED = 1 }; enum FreyaEvents @@ -619,7 +618,7 @@ class boss_freya : public CreatureScript Elder->AttackStop(); Elder->CombatStop(true); Elder->DeleteThreatList(); - Elder->GetAI()->DoAction(ACTION_ELDER_FREYA_KILLED); + Elder->AI()->DoAction(ACTION_ELDER_FREYA_KILLED); } } } @@ -705,19 +704,10 @@ class boss_elder_brightleaf : public CreatureScript Talk(SAY_ELDER_SLAY); } - void JustDied(Unit* killer) override + void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_ELDER_DEATH); - - if (killer->GetTypeId() == TYPEID_PLAYER) - { - if (Creature* Ironbranch = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_IRONBRANCH))) - Ironbranch->AI()->DoAction(ACTION_ELDER_DEATH); - - if (Creature* Stonebark = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_STONEBARK))) - Stonebark->AI()->DoAction(ACTION_ELDER_DEATH); - } } void EnterCombat(Unit* /*who*/) override @@ -812,19 +802,10 @@ class boss_elder_stonebark : public CreatureScript Talk(SAY_ELDER_SLAY); } - void JustDied(Unit* killer) override + void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_ELDER_DEATH); - - if (killer->GetTypeId() == TYPEID_PLAYER) - { - if (Creature* Ironbranch = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_IRONBRANCH))) - Ironbranch->AI()->DoAction(ACTION_ELDER_DEATH); - - if (Creature* Brightleaf = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_BRIGHTLEAF))) - Brightleaf->AI()->DoAction(ACTION_ELDER_DEATH); - } } void EnterCombat(Unit* /*who*/) override @@ -925,19 +906,10 @@ class boss_elder_ironbranch : public CreatureScript Talk(SAY_ELDER_SLAY); } - void JustDied(Unit* killer) override + void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_ELDER_DEATH); - - if (killer->GetTypeId() == TYPEID_PLAYER) - { - if (Creature* Brightleaf = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_BRIGHTLEAF))) - Brightleaf->AI()->DoAction(ACTION_ELDER_DEATH); - - if (Creature* Stonebark = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_STONEBARK))) - Stonebark->AI()->DoAction(ACTION_ELDER_DEATH); - } } void EnterCombat(Unit* /*who*/) override diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp index 09d95b34521..cbd24141bdf 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp @@ -415,7 +415,7 @@ class npc_saronite_vapors : public CreatureScript if (damage >= me->GetHealth()) { damage = 0; - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->SetStandState(UNIT_STAND_STATE_DEAD); me->SetHealth(me->GetMaxHealth()); me->RemoveAllAuras(); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp index c35a5936822..c03a1c6fbc1 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp @@ -30,6 +30,8 @@ Destroying of Toasty Fires */ +/* @todo Hodir aggro behavior is wonky. He gets set to _PASSIVE, but never to _AGGRESSIVE unless you kill an ice block which doesn't spawn unless you have*/ + enum HodirYells { SAY_AGGRO = 0, @@ -184,7 +186,7 @@ class npc_flash_freeze : public CreatureScript Initialize(); instance = me->GetInstanceScript(); me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); } void Initialize() @@ -259,7 +261,7 @@ class npc_ice_block : public CreatureScript { instance = me->GetInstanceScript(); me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); } InstanceScript* instance; @@ -269,7 +271,7 @@ class npc_ice_block : public CreatureScript void IsSummonedBy(Unit* summoner) override { targetGUID = summoner->GetGUID(); - summoner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); + summoner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); me->SetInCombatWith(summoner); me->AddThreat(summoner, 250.0f); summoner->AddThreat(me, 250.0f); @@ -285,7 +287,7 @@ class npc_ice_block : public CreatureScript { if (Creature* Helper = ObjectAccessor::GetCreature(*me, targetGUID)) { - Helper->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); + Helper->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); if (Creature* Hodir = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_HODIR))) { @@ -375,7 +377,7 @@ class boss_hodir : public CreatureScript Talk(SAY_SLAY); } - void DamageTaken(Unit* /*who*/, uint32& damage) override + void DamageTaken(Unit* who, uint32& damage) override { if (damage >= me->GetHealth()) { @@ -388,7 +390,7 @@ class boss_hodir : public CreatureScript me->RemoveAllAttackers(); me->AttackStop(); me->SetReactState(REACT_PASSIVE); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); me->InterruptNonMeleeSpells(true); me->StopMoving(); me->GetMotionMaster()->Clear(); @@ -403,6 +405,12 @@ class boss_hodir : public CreatureScript _JustDied(); } + else if (!me->IsInCombat()) + { + me->SetReactState(REACT_AGGRESSIVE); + me->AI()->DoZoneInCombat(); + me->AI()->AttackStart(who); + } } void UpdateAI(uint32 diff) override @@ -539,7 +547,7 @@ class npc_icicle : public CreatureScript { Initialize(); me->SetDisplayId(me->GetCreatureTemplate()->Modelid1); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_NOT_SELECTABLE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); } @@ -593,7 +601,7 @@ class npc_snowpacked_icicle : public CreatureScript { Initialize(); me->SetDisplayId(me->GetCreatureTemplate()->Modelid2); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); me->SetReactState(REACT_PASSIVE); } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp index cd214a0114f..a50643c5deb 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp @@ -178,7 +178,7 @@ class boss_ignis : public CreatureScript { summon->setFaction(16); summon->SetReactState(REACT_AGGRESSIVE); - summon->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED | UNIT_FLAG_DISABLE_MOVE); + summon->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED | UNIT_FLAG_REMOVE_CLIENT_CONTROL | UNIT_FLAG_IMMUNE_TO_PC); } summon->AI()->AttackStart(me->GetVictim()); @@ -375,7 +375,7 @@ class npc_scorch_ground : public CreatureScript npc_scorch_groundAI(Creature* creature) : ScriptedAI(creature) { Initialize(); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE |UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL |UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); creature->SetDisplayId(16925); //model 2 in db cannot overwrite wdb fields } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp index 470ad388fff..45d4fa58a03 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp @@ -104,7 +104,7 @@ class boss_kologarn : public CreatureScript left(false), right(false) { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_REMOVE_CLIENT_CONTROL); DoCast(SPELL_KOLOGARN_REDUCE_PARRY); SetCombatMovement(false); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp index e694433c614..a965f8b39ff 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp @@ -359,9 +359,9 @@ static bool IsEncounterFinished(Unit* who) if (!mkii || !vx001 || !aerial) return false; - if (mkii->getStandState() == UNIT_STAND_STATE_DEAD && - vx001->getStandState() == UNIT_STAND_STATE_DEAD && - aerial->getStandState() == UNIT_STAND_STATE_DEAD) + if (mkii->GetStandState() == UNIT_STAND_STATE_DEAD && + vx001->GetStandState() == UNIT_STAND_STATE_DEAD && + aerial->GetStandState() == UNIT_STAND_STATE_DEAD) { who->Kill(mkii); who->Kill(vx001); @@ -644,10 +644,10 @@ class boss_mimiron : public CreatureScript { if (Creature* computer = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_COMPUTER))) computer->AI()->DoAction(DO_DEACTIVATE_COMPUTER); - me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION_FIREFIGHTER, GO_CACHE_OF_INNOVATION_FIREFIGHTER_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, 0.f, 0.f, 0.9999619f, 0.008734641f, 604800); + me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION_FIREFIGHTER, GO_CACHE_OF_INNOVATION_FIREFIGHTER_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, G3D::Quat(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); } else - me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION, GO_CACHE_OF_INNOVATION_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, 0.f, 0.f, 0.9999619f, 0.008734641f, 604800); + me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION, GO_CACHE_OF_INNOVATION_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, G3D::Quat(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); events.ScheduleEvent(EVENT_OUTTRO_3, 11000); break; case EVENT_OUTTRO_3: @@ -703,7 +703,7 @@ class boss_leviathan_mk_ii : public CreatureScript if (Unit* turret = me->GetVehicleKit()->GetPassenger(3)) turret->KillSelf(); - me->SetSpeed(MOVE_RUN, 1.5f, true); + me->SetSpeedRate(MOVE_RUN, 1.5f); me->GetMotionMaster()->MovePoint(WP_MKII_P1_IDLE, VehicleRelocation[WP_MKII_P1_IDLE]); } else if (events.IsInPhase(PHASE_VOL7RON)) @@ -972,7 +972,7 @@ class boss_vx_001 : public CreatureScript events.ScheduleEvent(EVENT_FLAME_SUPPRESSANT_VX, 6000); // Missing break intended. case DO_START_VX001: - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); me->RemoveAurasDueToSpell(SPELL_FREEZE_ANIM); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); // Remove emotestate. //me->SetUInt32Value(UNIT_FIELD_BYTES_1, 33554432); Blizzard handles hover animation like this it seems. @@ -1145,7 +1145,7 @@ class boss_aerial_command_unit : public CreatureScript events.ScheduleEvent(EVENT_SUMMON_FIRE_BOTS, 1000, 0, PHASE_AERIAL_COMMAND_UNIT); // Missing break intended. case DO_START_AERIAL: - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); me->SetReactState(REACT_AGGRESSIVE); events.SetPhase(PHASE_AERIAL_COMMAND_UNIT); @@ -2759,7 +2759,7 @@ class achievement_setup_boom : public AchievementCriteriaScript public: achievement_setup_boom() : AchievementCriteriaScript("achievement_setup_boom") { } - bool OnCheck(Player* /*source*/, Unit* target) + bool OnCheck(Player* /*source*/, Unit* target) override { return target && target->GetAI()->GetData(DATA_SETUP_BOMB); } @@ -2770,7 +2770,7 @@ class achievement_setup_mine : public AchievementCriteriaScript public: achievement_setup_mine() : AchievementCriteriaScript("achievement_setup_mine") { } - bool OnCheck(Player* /*source*/, Unit* target) + bool OnCheck(Player* /*source*/, Unit* target) override { return target && target->GetAI()->GetData(DATA_SETUP_MINE); } @@ -2781,7 +2781,7 @@ class achievement_setup_rocket : public AchievementCriteriaScript public: achievement_setup_rocket() : AchievementCriteriaScript("achievement_setup_rocket") { } - bool OnCheck(Player* /*source*/, Unit* target) + bool OnCheck(Player* /*source*/, Unit* target) override { return target && target->GetAI()->GetData(DATA_SETUP_ROCKET); } @@ -2792,7 +2792,7 @@ class achievement_firefighter : public AchievementCriteriaScript public: achievement_firefighter() : AchievementCriteriaScript("achievement_firefighter") { } - bool OnCheck(Player* /*source*/, Unit* target) + bool OnCheck(Player* /*source*/, Unit* target) override { return target && target->GetAI()->GetData(DATA_FIREFIGHTER); } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp index f5337b2dca5..a0ea2bd3d57 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp @@ -242,7 +242,7 @@ class boss_razorscale_controller : public CreatureScript break; case ACTION_PLACE_BROKEN_HARPOON: for (uint8 n = 0; n < RAID_MODE(2, 4); n++) - me->SummonGameObject(GO_RAZOR_BROKEN_HARPOON, PosHarpoon[n].GetPositionX(), PosHarpoon[n].GetPositionY(), PosHarpoon[n].GetPositionZ(), 2.286f, 0, 0, 0, 0, 180); + me->SummonGameObject(GO_RAZOR_BROKEN_HARPOON, PosHarpoon[n].GetPositionX(), PosHarpoon[n].GetPositionY(), PosHarpoon[n].GetPositionZ(), 2.286f, G3D::Quat(), 180); break; } } @@ -257,7 +257,7 @@ class boss_razorscale_controller : public CreatureScript { case EVENT_BUILD_HARPOON_1: Talk(EMOTE_HARPOON); - if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_1, PosHarpoon[0].GetPositionX(), PosHarpoon[0].GetPositionY(), PosHarpoon[0].GetPositionZ(), 4.790f, 0.0f, 0.0f, 0.0f, 0.0f, uint32(me->GetRespawnTime()))) + if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_1, PosHarpoon[0].GetPositionX(), PosHarpoon[0].GetPositionY(), PosHarpoon[0].GetPositionZ(), 4.790f, G3D::Quat(), uint32(me->GetRespawnTime()))) { if (GameObject* BrokenHarpoon = Harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) //only nearest broken harpoon BrokenHarpoon->RemoveFromWorld(); @@ -267,7 +267,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_2: Talk(EMOTE_HARPOON); - if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_2, PosHarpoon[1].GetPositionX(), PosHarpoon[1].GetPositionY(), PosHarpoon[1].GetPositionZ(), 4.659f, 0, 0, 0, 0, uint32(me->GetRespawnTime()))) + if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_2, PosHarpoon[1].GetPositionX(), PosHarpoon[1].GetPositionY(), PosHarpoon[1].GetPositionZ(), 4.659f, G3D::Quat(), uint32(me->GetRespawnTime()))) { if (GameObject* BrokenHarpoon = Harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) BrokenHarpoon->RemoveFromWorld(); @@ -276,7 +276,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_3: Talk(EMOTE_HARPOON); - if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_3, PosHarpoon[2].GetPositionX(), PosHarpoon[2].GetPositionY(), PosHarpoon[2].GetPositionZ(), 5.382f, 0, 0, 0, 0, uint32(me->GetRespawnTime()))) + if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_3, PosHarpoon[2].GetPositionX(), PosHarpoon[2].GetPositionY(), PosHarpoon[2].GetPositionZ(), 5.382f, G3D::Quat(), uint32(me->GetRespawnTime()))) { if (GameObject* BrokenHarpoon = Harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) BrokenHarpoon->RemoveFromWorld(); @@ -286,7 +286,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_4: Talk(EMOTE_HARPOON); - if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_4, PosHarpoon[3].GetPositionX(), PosHarpoon[3].GetPositionY(), PosHarpoon[3].GetPositionZ(), 4.266f, 0, 0, 0, 0, uint32(me->GetRespawnTime()))) + if (GameObject* Harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_4, PosHarpoon[3].GetPositionX(), PosHarpoon[3].GetPositionY(), PosHarpoon[3].GetPositionZ(), 4.266f, G3D::Quat(), uint32(me->GetRespawnTime()))) { if (GameObject* BrokenHarpoon = Harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) BrokenHarpoon->RemoveFromWorld(); @@ -366,7 +366,7 @@ class boss_razorscale : public CreatureScript _EnterCombat(); if (Creature* controller = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_RAZORSCALE_CONTROL))) controller->AI()->DoAction(ACTION_HARPOON_BUILD); - me->SetSpeed(MOVE_FLIGHT, 3.0f, true); + me->SetSpeedRate(MOVE_FLIGHT, 3.0f); me->SetReactState(REACT_PASSIVE); phase = PHASE_GROUND; events.SetPhase(PHASE_GROUND); @@ -550,7 +550,7 @@ class boss_razorscale : public CreatureScript me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED | UNIT_FLAG_PACIFIED); me->SetReactState(REACT_AGGRESSIVE); me->RemoveAurasDueToSpell(SPELL_HARPOON_TRIGGER); - me->SetSpeed(MOVE_FLIGHT, 1.0f, true); + me->SetSpeedRate(MOVE_FLIGHT, 1.0f); PermaGround = true; DoCastAOE(SPELL_FLAMEBREATH); events.ScheduleEvent(EVENT_FLAME, 15000, 0, PHASE_PERMAGROUND); @@ -677,7 +677,7 @@ class npc_expedition_commander : public CreatureScript if (Creature* summonedEngineer = me->SummonCreature(NPC_ENGINEER, PosEngSpawn, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000)) { summonedEngineer->SetWalk(false); - summonedEngineer->SetSpeed(MOVE_RUN, 0.5f); + summonedEngineer->SetSpeedRate(MOVE_RUN, 0.5f); summonedEngineer->SetHomePosition(PosEngRepair[n]); summonedEngineer->GetMotionMaster()->MoveTargetedHome(); Engineer[n] = summonedEngineer->GetGUID(); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp index 8cb20eadc9f..f3aeec85af2 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp @@ -637,7 +637,7 @@ class BoomEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { // This hack is here because we suspect our implementation of spell effect execution on targets // is done in the wrong order. We suspect that EFFECT_0 needs to be applied on all targets, diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp index 7da67171b5c..675268b4e93 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp @@ -230,6 +230,9 @@ enum Spells // Descend Into Madness SPELL_TELEPORT_PORTAL_VISUAL = 64416, + SPELL_TELEPORT_TO_STORMWIND_ILLUSION = 63989, + SPELL_TELEPORT_TO_CHAMBER_ILLUSION = 63997, + SPELL_TELEPORT_TO_ICECROWN_ILLUSION = 63998, // Illusions SPELL_GRIM_REPRISAL = 63305, @@ -395,6 +398,14 @@ enum MiscData { ACHIEV_TIMED_START_EVENT = 21001, SOUND_LUNATIC_GAZE = 15757, + MAX_ILLUSION_ROOMS = 3 +}; + +uint32 const IllusionSpells[MAX_ILLUSION_ROOMS] +{ + SPELL_TELEPORT_TO_CHAMBER_ILLUSION, + SPELL_TELEPORT_TO_ICECROWN_ILLUSION, + SPELL_TELEPORT_TO_STORMWIND_ILLUSION }; class StartAttackEvent : public BasicEvent @@ -405,7 +416,7 @@ class StartAttackEvent : public BasicEvent { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) + bool Execute(uint64 /*time*/, uint32 /*diff*/) override { _owner->SetReactState(REACT_AGGRESSIVE); if (Creature* _summoner = ObjectAccessor::GetCreature(*_owner, _summonerGuid)) @@ -1419,7 +1430,11 @@ class npc_descend_into_madness : public CreatureScript { if (!result) return; + clicker->RemoveAurasDueToSpell(SPELL_BRAIN_LINK); + uint32 illusion = _instance->GetData(DATA_ILLUSION); + if (illusion < MAX_ILLUSION_ROOMS) + DoCast(clicker, IllusionSpells[illusion], true); me->DespawnOrUnsummon(); } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp index 1af45f3031a..3dec0c60991 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp @@ -102,7 +102,7 @@ public: Sequence[i] = Phase(i); /// This ensures a random order and only executes each phase once. - std::random_shuffle(Sequence, Sequence + PHASE_GORTOK_PALEHOOF); + Trinity::Containers::RandomShuffle(Sequence); uiArcingSmashTimer = 15000; uiImpaleTimer = 12000; @@ -118,7 +118,7 @@ public: uint32 uiWhiteringRoarTimer; Phase currentPhase; uint8 AddCount; - Phase Sequence[4]; + std::array<Phase, 4> Sequence; void Reset() override { @@ -746,7 +746,7 @@ public: //! HACK: Creature's can't have MOVEMENTFLAG_FLYING me->AddUnitMovementFlag(MOVEMENTFLAG_FLYING); me->RemoveAurasDueToSpell(SPELL_ORB_VISUAL); - me->SetSpeed(MOVE_FLIGHT, 0.5f); + me->SetSpeedRate(MOVE_FLIGHT, 0.5f); } void UpdateAI(uint32 diff) override diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp index d7b65093898..7615217a794 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp @@ -209,7 +209,7 @@ public: Initialize(); Summons.DespawnAll(); - me->SetSpeed(MOVE_FLIGHT, 3.0f); + me->SetSpeedRate(MOVE_FLIGHT, 3.0f); if ((ObjectAccessor::GetCreature(*me, m_uiGraufGUID) == NULL) && !me->IsMounted()) me->SummonCreature(NPC_GRAUF, Location[0].GetPositionX(), Location[0].GetPositionY(), Location[0].GetPositionZ(), 3.0f); instance->SetBossState(DATA_SKADI_THE_RUTHLESS, NOT_STARTED); diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp index 8f2d5a61770..28ca7f4ef3b 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp @@ -19,9 +19,9 @@ #include "InstanceScript.h" #include "utgarde_pinnacle.h" -BossBoundaryData const boundaries = +BossBoundaryData const boundaries = { - { DATA_KING_YMIRON, new RectangleBoundary(340.0f, 450.0f, -412.0f, -275.0f) } + { DATA_KING_YMIRON, new RectangleBoundary(340.0f, 443.0f, -412.0f, -275.0f) } }; DoorData const doorData[] = diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp index b89c11147b6..df3fa266191 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp @@ -115,6 +115,7 @@ class boss_archavon : public CreatureScript DoCastVictim(SPELL_STOMP); events.ScheduleEvent(EVENT_IMPALE, 3000); events.ScheduleEvent(EVENT_STOMP, 45000); + Talk(EMOTE_LEAP, me->GetVictim()); break; case EVENT_IMPALE: DoCastVictim(SPELL_IMPALE); diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp index 06ebcbdc2fb..e7305e53808 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp @@ -247,7 +247,7 @@ class npc_frozen_orb_stalker : public CreatureScript npc_frozen_orb_stalkerAI(Creature* creature) : ScriptedAI(creature) { creature->SetVisible(false); - creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_REMOVE_CLIENT_CONTROL); creature->SetReactState(REACT_PASSIVE); instance = creature->GetInstanceScript(); diff --git a/src/server/scripts/Northrend/northrend_script_loader.cpp b/src/server/scripts/Northrend/northrend_script_loader.cpp new file mode 100644 index 00000000000..d84bb1c4072 --- /dev/null +++ b/src/server/scripts/Northrend/northrend_script_loader.cpp @@ -0,0 +1,376 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_boss_slad_ran(); +void AddSC_boss_moorabi(); +void AddSC_boss_drakkari_colossus(); +void AddSC_boss_gal_darah(); +void AddSC_boss_eck(); +void AddSC_instance_gundrak(); + +// Azjol-Nerub - Azjol-Nerub +void AddSC_boss_krik_thir(); +void AddSC_boss_hadronox(); +void AddSC_boss_anub_arak(); +void AddSC_instance_azjol_nerub(); + +// Azjol-Nerub - Ahn'kahet +void AddSC_boss_elder_nadox(); +void AddSC_boss_taldaram(); +void AddSC_boss_amanitar(); +void AddSC_boss_jedoga_shadowseeker(); +void AddSC_boss_volazj(); +void AddSC_instance_ahnkahet(); + +// Drak'Tharon Keep +void AddSC_boss_trollgore(); +void AddSC_boss_novos(); +void AddSC_boss_king_dred(); +void AddSC_boss_tharon_ja(); +void AddSC_instance_drak_tharon_keep(); + +void AddSC_boss_argent_challenge(); //Trial of the Champion +void AddSC_boss_black_knight(); +void AddSC_boss_grand_champions(); +void AddSC_instance_trial_of_the_champion(); +void AddSC_trial_of_the_champion(); +void AddSC_boss_anubarak_trial(); //Trial of the Crusader +void AddSC_boss_faction_champions(); +void AddSC_boss_jaraxxus(); +void AddSC_boss_northrend_beasts(); +void AddSC_boss_twin_valkyr(); +void AddSC_trial_of_the_crusader(); +void AddSC_instance_trial_of_the_crusader(); +void AddSC_boss_anubrekhan(); //Naxxramas +void AddSC_boss_maexxna(); +void AddSC_boss_patchwerk(); +void AddSC_boss_grobbulus(); +void AddSC_boss_razuvious(); +void AddSC_boss_kelthuzad(); +void AddSC_boss_loatheb(); +void AddSC_boss_noth(); +void AddSC_boss_gluth(); +void AddSC_boss_sapphiron(); +void AddSC_boss_four_horsemen(); +void AddSC_boss_faerlina(); +void AddSC_boss_heigan(); +void AddSC_boss_gothik(); +void AddSC_boss_thaddius(); +void AddSC_instance_naxxramas(); +void AddSC_boss_nexus_commanders(); // The Nexus Nexus +void AddSC_boss_magus_telestra(); +void AddSC_boss_anomalus(); +void AddSC_boss_ormorok(); +void AddSC_boss_keristrasza(); +void AddSC_instance_nexus(); +void AddSC_boss_drakos(); //The Nexus The Oculus +void AddSC_boss_urom(); +void AddSC_boss_varos(); +void AddSC_boss_eregos(); +void AddSC_instance_oculus(); +void AddSC_oculus(); +void AddSC_boss_malygos(); // The Nexus: Eye of Eternity +void AddSC_instance_eye_of_eternity(); +void AddSC_boss_sartharion(); //Obsidian Sanctum +void AddSC_obsidian_sanctum(); +void AddSC_instance_obsidian_sanctum(); +void AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning +void AddSC_boss_loken(); +void AddSC_boss_ionar(); +void AddSC_boss_volkhan(); +void AddSC_instance_halls_of_lightning(); +void AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone +void AddSC_boss_krystallus(); +void AddSC_boss_sjonnir(); +void AddSC_instance_halls_of_stone(); +void AddSC_halls_of_stone(); +void AddSC_boss_auriaya(); //Ulduar Ulduar +void AddSC_boss_flame_leviathan(); +void AddSC_boss_ignis(); +void AddSC_boss_razorscale(); +void AddSC_boss_xt002(); +void AddSC_boss_kologarn(); +void AddSC_boss_assembly_of_iron(); +void AddSC_boss_general_vezax(); +void AddSC_boss_mimiron(); +void AddSC_boss_hodir(); +void AddSC_boss_freya(); +void AddSC_boss_yogg_saron(); +void AddSC_boss_algalon_the_observer(); +void AddSC_instance_ulduar(); + +// Utgarde Keep - Utgarde Keep +void AddSC_boss_keleseth(); +void AddSC_boss_skarvald_dalronn(); +void AddSC_boss_ingvar_the_plunderer(); +void AddSC_instance_utgarde_keep(); +void AddSC_utgarde_keep(); + +// Utgarde Keep - Utgarde Pinnacle +void AddSC_boss_svala(); +void AddSC_boss_palehoof(); +void AddSC_boss_skadi(); +void AddSC_boss_ymiron(); +void AddSC_instance_utgarde_pinnacle(); + +// Vault of Archavon +void AddSC_boss_archavon(); +void AddSC_boss_emalon(); +void AddSC_boss_koralon(); +void AddSC_boss_toravon(); +void AddSC_instance_vault_of_archavon(); + +void AddSC_boss_cyanigosa(); //Violet Hold +void AddSC_boss_erekem(); +void AddSC_boss_ichoron(); +void AddSC_boss_lavanthor(); +void AddSC_boss_moragg(); +void AddSC_boss_xevozz(); +void AddSC_boss_zuramat(); +void AddSC_instance_violet_hold(); +void AddSC_violet_hold(); +void AddSC_instance_forge_of_souls(); //Forge of Souls +void AddSC_forge_of_souls(); +void AddSC_boss_bronjahm(); +void AddSC_boss_devourer_of_souls(); +void AddSC_instance_pit_of_saron(); //Pit of Saron +void AddSC_pit_of_saron(); +void AddSC_boss_garfrost(); +void AddSC_boss_ick(); +void AddSC_boss_tyrannus(); +void AddSC_instance_halls_of_reflection(); // Halls of Reflection +void AddSC_halls_of_reflection(); +void AddSC_boss_falric(); +void AddSC_boss_marwyn(); +void AddSC_boss_lord_marrowgar(); // Icecrown Citadel +void AddSC_boss_lady_deathwhisper(); +void AddSC_boss_icecrown_gunship_battle(); +void AddSC_boss_deathbringer_saurfang(); +void AddSC_boss_festergut(); +void AddSC_boss_rotface(); +void AddSC_boss_professor_putricide(); +void AddSC_boss_blood_prince_council(); +void AddSC_boss_blood_queen_lana_thel(); +void AddSC_boss_valithria_dreamwalker(); +void AddSC_boss_sindragosa(); +void AddSC_boss_the_lich_king(); +void AddSC_icecrown_citadel_teleport(); +void AddSC_instance_icecrown_citadel(); +void AddSC_icecrown_citadel(); +void AddSC_instance_ruby_sanctum(); // Ruby Sanctum +void AddSC_ruby_sanctum(); +void AddSC_boss_baltharus_the_warborn(); +void AddSC_boss_saviana_ragefire(); +void AddSC_boss_general_zarithrian(); +void AddSC_boss_halion(); +void AddSC_isle_of_conquest(); // Isle of Conquest +void AddSC_boss_ioc_horde_alliance(); + +void AddSC_dalaran(); +void AddSC_borean_tundra(); +void AddSC_dragonblight(); +void AddSC_grizzly_hills(); +void AddSC_howling_fjord(); +void AddSC_icecrown(); +void AddSC_sholazar_basin(); +void AddSC_storm_peaks(); +void AddSC_wintergrasp(); +void AddSC_zuldrak(); +void AddSC_crystalsong_forest(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddNorthrendScripts() +{ + AddSC_boss_slad_ran(); //Gundrak + AddSC_boss_moorabi(); + AddSC_boss_drakkari_colossus(); + AddSC_boss_gal_darah(); + AddSC_boss_eck(); + AddSC_instance_gundrak(); + + // Azjol-Nerub - Ahn'kahet + AddSC_boss_elder_nadox(); + AddSC_boss_taldaram(); + AddSC_boss_amanitar(); + AddSC_boss_jedoga_shadowseeker(); + AddSC_boss_volazj(); + AddSC_instance_ahnkahet(); + + // Azjol-Nerub - Azjol-Nerub + AddSC_boss_krik_thir(); + AddSC_boss_hadronox(); + AddSC_boss_anub_arak(); + AddSC_instance_azjol_nerub(); + + // Drak'Tharon Keep + AddSC_boss_trollgore(); + AddSC_boss_novos(); + AddSC_boss_king_dred(); + AddSC_boss_tharon_ja(); + AddSC_instance_drak_tharon_keep(); + + AddSC_boss_argent_challenge(); //Trial of the Champion + AddSC_boss_black_knight(); + AddSC_boss_grand_champions(); + AddSC_instance_trial_of_the_champion(); + AddSC_trial_of_the_champion(); + AddSC_boss_anubarak_trial(); //Trial of the Crusader + AddSC_boss_faction_champions(); + AddSC_boss_jaraxxus(); + AddSC_trial_of_the_crusader(); + AddSC_boss_twin_valkyr(); + AddSC_boss_northrend_beasts(); + AddSC_instance_trial_of_the_crusader(); + AddSC_boss_anubrekhan(); //Naxxramas + AddSC_boss_maexxna(); + AddSC_boss_patchwerk(); + AddSC_boss_grobbulus(); + AddSC_boss_razuvious(); + AddSC_boss_kelthuzad(); + AddSC_boss_loatheb(); + AddSC_boss_noth(); + AddSC_boss_gluth(); + AddSC_boss_sapphiron(); + AddSC_boss_four_horsemen(); + AddSC_boss_faerlina(); + AddSC_boss_heigan(); + AddSC_boss_gothik(); + AddSC_boss_thaddius(); + AddSC_instance_naxxramas(); + AddSC_boss_nexus_commanders(); // The Nexus Nexus + AddSC_boss_magus_telestra(); + AddSC_boss_anomalus(); + AddSC_boss_ormorok(); + AddSC_boss_keristrasza(); + AddSC_instance_nexus(); + AddSC_boss_drakos(); //The Nexus The Oculus + AddSC_boss_urom(); + AddSC_boss_varos(); + AddSC_boss_eregos(); + AddSC_instance_oculus(); + AddSC_oculus(); + AddSC_boss_malygos(); // The Nexus: Eye of Eternity + AddSC_instance_eye_of_eternity(); + AddSC_boss_sartharion(); //Obsidian Sanctum + AddSC_obsidian_sanctum(); + AddSC_instance_obsidian_sanctum(); + AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning + AddSC_boss_loken(); + AddSC_boss_ionar(); + AddSC_boss_volkhan(); + AddSC_instance_halls_of_lightning(); + AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone + AddSC_boss_krystallus(); + AddSC_boss_sjonnir(); + AddSC_instance_halls_of_stone(); + AddSC_halls_of_stone(); + AddSC_boss_auriaya(); //Ulduar Ulduar + AddSC_boss_flame_leviathan(); + AddSC_boss_ignis(); + AddSC_boss_razorscale(); + AddSC_boss_xt002(); + AddSC_boss_general_vezax(); + AddSC_boss_assembly_of_iron(); + AddSC_boss_kologarn(); + AddSC_boss_mimiron(); + AddSC_boss_hodir(); + AddSC_boss_freya(); + AddSC_boss_yogg_saron(); + AddSC_boss_algalon_the_observer(); + AddSC_instance_ulduar(); + + // Utgarde Keep - Utgarde Keep + AddSC_boss_keleseth(); + AddSC_boss_skarvald_dalronn(); + AddSC_boss_ingvar_the_plunderer(); + AddSC_instance_utgarde_keep(); + AddSC_utgarde_keep(); + + // Utgarde Keep - Utgarde Pinnacle + AddSC_boss_svala(); + AddSC_boss_palehoof(); + AddSC_boss_skadi(); + AddSC_boss_ymiron(); + AddSC_instance_utgarde_pinnacle(); + + // Vault of Archavon + AddSC_boss_archavon(); + AddSC_boss_emalon(); + AddSC_boss_koralon(); + AddSC_boss_toravon(); + AddSC_instance_vault_of_archavon(); + + AddSC_boss_cyanigosa(); //Violet Hold + AddSC_boss_erekem(); + AddSC_boss_ichoron(); + AddSC_boss_lavanthor(); + AddSC_boss_moragg(); + AddSC_boss_xevozz(); + AddSC_boss_zuramat(); + AddSC_instance_violet_hold(); + AddSC_violet_hold(); + AddSC_instance_forge_of_souls(); //Forge of Souls + AddSC_forge_of_souls(); + AddSC_boss_bronjahm(); + AddSC_boss_devourer_of_souls(); + AddSC_instance_pit_of_saron(); //Pit of Saron + AddSC_pit_of_saron(); + AddSC_boss_garfrost(); + AddSC_boss_ick(); + AddSC_boss_tyrannus(); + AddSC_instance_halls_of_reflection(); // Halls of Reflection + AddSC_halls_of_reflection(); + AddSC_boss_falric(); + AddSC_boss_marwyn(); + AddSC_boss_lord_marrowgar(); // Icecrown Citadel + AddSC_boss_lady_deathwhisper(); + AddSC_boss_icecrown_gunship_battle(); + AddSC_boss_deathbringer_saurfang(); + AddSC_boss_festergut(); + AddSC_boss_rotface(); + AddSC_boss_professor_putricide(); + AddSC_boss_blood_prince_council(); + AddSC_boss_blood_queen_lana_thel(); + AddSC_boss_valithria_dreamwalker(); + AddSC_boss_sindragosa(); + AddSC_boss_the_lich_king(); + AddSC_icecrown_citadel_teleport(); + AddSC_instance_icecrown_citadel(); + AddSC_icecrown_citadel(); + AddSC_instance_ruby_sanctum(); // Ruby Sanctum + AddSC_ruby_sanctum(); + AddSC_boss_baltharus_the_warborn(); + AddSC_boss_saviana_ragefire(); + AddSC_boss_general_zarithrian(); + AddSC_boss_halion(); + AddSC_isle_of_conquest(); // Isle of Conquest + AddSC_boss_ioc_horde_alliance(); + + AddSC_dalaran(); + AddSC_borean_tundra(); + AddSC_dragonblight(); + AddSC_grizzly_hills(); + AddSC_howling_fjord(); + AddSC_icecrown(); + AddSC_sholazar_basin(); + AddSC_storm_peaks(); + AddSC_wintergrasp(); + AddSC_zuldrak(); + AddSC_crystalsong_forest(); +} diff --git a/src/server/scripts/Northrend/zone_borean_tundra.cpp b/src/server/scripts/Northrend/zone_borean_tundra.cpp index 698fd510411..d9315315c58 100644 --- a/src/server/scripts/Northrend/zone_borean_tundra.cpp +++ b/src/server/scripts/Northrend/zone_borean_tundra.cpp @@ -2274,7 +2274,8 @@ public: void DoAction(int32 /*iParam*/) override { me->StopMoving(); - me->SetUInt32Value(UNIT_NPC_FLAGS, 0); + me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); + me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); if (Player* player = ObjectAccessor::GetPlayer(*me, uiPlayerGUID)) me->SetFacingToObject(player); uiEventTimer = 3000; @@ -2303,7 +2304,6 @@ public: switch (me->GetEntry()) { case NPC_SALTY_JOHN_THORPE: - me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); Talk(SAY_HIDDEN_CULTIST_1); uiEventTimer = 5000; uiEventPhase = 2; @@ -2314,7 +2314,8 @@ public: uiEventPhase = 2; break; case NPC_TOM_HEGGER: - Talk(SAY_HIDDEN_CULTIST_3); + if (Player* player = ObjectAccessor::GetPlayer(*me, uiPlayerGUID)) + Talk(SAY_HIDDEN_CULTIST_3, player); uiEventTimer = 5000; uiEventPhase = 2; break; diff --git a/src/server/scripts/Northrend/zone_dragonblight.cpp b/src/server/scripts/Northrend/zone_dragonblight.cpp index 2ec2af80624..d7ff1e5cb4d 100644 --- a/src/server/scripts/Northrend/zone_dragonblight.cpp +++ b/src/server/scripts/Northrend/zone_dragonblight.cpp @@ -360,7 +360,7 @@ class npc_commander_eligor_dawnbringer : public CreatureScript uint8 talkWing; }; - CreatureAI* GetAI(Creature* creature) const + CreatureAI* GetAI(Creature* creature) const override { return new npc_commander_eligor_dawnbringerAI(creature); } @@ -695,7 +695,7 @@ class npc_torturer_lecraft : public CreatureScript ObjectGuid _playerGUID; }; - CreatureAI* GetAI(Creature* creature) const + CreatureAI* GetAI(Creature* creature) const override { return new npc_torturer_lecraftAI(creature); } diff --git a/src/server/scripts/Northrend/zone_grizzly_hills.cpp b/src/server/scripts/Northrend/zone_grizzly_hills.cpp index 59802165a94..adade245c2b 100644 --- a/src/server/scripts/Northrend/zone_grizzly_hills.cpp +++ b/src/server/scripts/Northrend/zone_grizzly_hills.cpp @@ -22,6 +22,7 @@ #include "Player.h" #include "SpellScript.h" #include "CreatureTextMgr.h" +#include "CombatAI.h" /*###### ## Quest 12027: Mr. Floppy's Perilous Adventure @@ -854,6 +855,260 @@ class spell_infected_worgen_bite : public SpellScriptLoader } }; +/*###### +## Quest: Riding the Red Rocket +######*/ + +enum RedRocket +{ + SPELL_VEHICLE_WARHEAD_FUSE = 49107, + SPELL_ALLIANCE_KILL_CREDIT_TORPEDO = 49510, + SPELL_HORDE_KILL_CREDIT_TORPEDO = 49340, + NPC_HORDE_LUMBERBOAT = 27702, + NPC_ALLIANCE_LUMBERBOAT = 27688, + SPELL_DETONATE = 49250 +}; + +class npc_rocket_propelled_warhead : public CreatureScript +{ +public: + npc_rocket_propelled_warhead() : CreatureScript("npc_rocket_propelled_warhead") { } + + struct npc_rocket_propelled_warheadAI : public VehicleAI + { + npc_rocket_propelled_warheadAI(Creature* creature) : VehicleAI(creature) + { + _finished = false; + _faction = ALLIANCE; + } + + void PassengerBoarded(Unit* who, int8 /*seatId*/, bool apply) override + { + if (apply && who->ToPlayer()) + { + DoCast(me, SPELL_VEHICLE_WARHEAD_FUSE); + _faction = who->ToPlayer()->GetTeam(); + } + } + + void JustReachedHome() override + { + _finished = false; + me->SetVisible(true); + me->GetMotionMaster()->Clear(true); + } + + void DoAction(int32 /*action*/) override + { + FinishQuest(false, _faction); + } + + void SpellHit(Unit* caster, SpellInfo const* /*spellInfo*/) override + { + if (caster->GetEntry() == NPC_HORDE_LUMBERBOAT || caster->GetEntry() == NPC_ALLIANCE_LUMBERBOAT) + FinishQuest(true, _faction); + } + + void FinishQuest(bool success, uint32 faction) + { + if (_finished) + return; + + _finished = true; + + if (success) + DoCast(me, faction == ALLIANCE ? SPELL_ALLIANCE_KILL_CREDIT_TORPEDO : SPELL_HORDE_KILL_CREDIT_TORPEDO); + + DoCast(me, SPELL_DETONATE); + me->RemoveAllAuras(); + me->SetVisible(false); + me->GetMotionMaster()->MoveTargetedHome(); + } + + private: + uint32 _faction; + bool _finished; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_rocket_propelled_warheadAI(creature); + } +}; + +enum WarheadSpells +{ + SPELL_WARHEAD_Z_CHECK = 61678, + SPELL_WARHEAD_SEEKING_LUMBERSHIP = 49331, + SPELL_WARHEAD_FUSE = 49181 +}; +// 49107 - Vehicle: Warhead Fuse +class spell_vehicle_warhead_fuse : public SpellScriptLoader +{ +public: + spell_vehicle_warhead_fuse() : SpellScriptLoader("spell_vehicle_warhead_fuse") { } + + class spell_vehicle_warhead_fuse_SpellScript : public SpellScript + { + PrepareSpellScript(spell_vehicle_warhead_fuse_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_WARHEAD_Z_CHECK) || !sSpellMgr->GetSpellInfo(SPELL_WARHEAD_SEEKING_LUMBERSHIP) || !sSpellMgr->GetSpellInfo(SPELL_WARHEAD_FUSE)) + return false; + return true; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + Unit* caster = GetCaster(); + + caster->CastSpell(caster, SPELL_WARHEAD_Z_CHECK, true); + caster->CastSpell(caster, SPELL_WARHEAD_SEEKING_LUMBERSHIP, true); + caster->CastSpell(caster, SPELL_WARHEAD_FUSE, true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_vehicle_warhead_fuse_SpellScript::HandleDummy, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_vehicle_warhead_fuse_SpellScript(); + } +}; + +enum WarheadDenonate +{ + SPELL_PARACHUTE = 66154, + SPELL_TORPEDO_EXPLOSION = 49290, + NPC_ALLIANCE_LUMBERBOAT_EXPLOSIONS = 27689 +}; +// 49250 - Detonate +class spell_warhead_detonate : public SpellScriptLoader +{ +public: + spell_warhead_detonate() : SpellScriptLoader("spell_warhead_detonate") { } + + class spell_warhead_detonate_SpellScript : public SpellScript + { + PrepareSpellScript(spell_warhead_detonate_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_PARACHUTE) || !sSpellMgr->GetSpellInfo(SPELL_TORPEDO_EXPLOSION)) + return false; + return true; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + Unit* caster = GetCaster(); + Player* player = GetHitPlayer(); + if (!player) + return; + + player->ExitVehicle(); + float horizontalSpeed = 3.0f; + float verticalSpeed = 40.0f; + player->KnockbackFrom(caster->GetPositionX(), caster->GetPositionY(), horizontalSpeed, verticalSpeed); + caster->CastSpell(player, SPELL_PARACHUTE, true); + + std::list<Creature*> explosionBunnys; + caster->GetCreatureListWithEntryInGrid(explosionBunnys, NPC_ALLIANCE_LUMBERBOAT_EXPLOSIONS, 90.0f); + for (std::list<Creature*>::const_iterator itr = explosionBunnys.begin(); itr != explosionBunnys.end(); ++itr) + (*itr)->CastSpell((*itr), SPELL_TORPEDO_EXPLOSION, true); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_warhead_detonate_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_warhead_detonate_SpellScript(); + } +}; + +// 61678 - Z Check +class spell_z_check : public SpellScriptLoader +{ +public: + spell_z_check() : SpellScriptLoader("spell_z_check") { } + + class spell_z_check_AuraScript : public AuraScript + { + PrepareAuraScript(spell_z_check_AuraScript); + + public: + spell_z_check_AuraScript() + { + _posZ = 0.0f; + } + + void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + _posZ = GetTarget()->GetPositionZ(); + } + + void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) + { + PreventDefaultAction(); + + if (_posZ != GetTarget()->GetPositionZ()) + if (Creature* target = GetTarget()->ToCreature()) + target->AI()->DoAction(0); + } + + private: + float _posZ; + + void Register() override + { + OnEffectApply += AuraEffectApplyFn(spell_z_check_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); + OnEffectPeriodic += AuraEffectPeriodicFn(spell_z_check_AuraScript::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_z_check_AuraScript(); + } +}; + +// 49181 - Warhead Fuse +class spell_warhead_fuse : public SpellScriptLoader +{ +public: + spell_warhead_fuse() : SpellScriptLoader("spell_warhead_fuse") { } + + class spell_warhead_fuse_AuraScript : public AuraScript + { + PrepareAuraScript(spell_warhead_fuse_AuraScript); + + void HandleOnEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + if (Unit* rocketUnit = GetTarget()->GetVehicleBase()) + if (Creature* rocketCrea = rocketUnit->ToCreature()) + rocketCrea->AI()->DoAction(0); + } + + void Register() override + { + OnEffectRemove += AuraEffectRemoveFn(spell_warhead_fuse_AuraScript::HandleOnEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_warhead_fuse_AuraScript(); + } +}; + void AddSC_grizzly_hills() { new npc_emily(); @@ -866,4 +1121,9 @@ void AddSC_grizzly_hills() new npc_lake_frog(); new spell_shredder_delivery(); new spell_infected_worgen_bite(); + new npc_rocket_propelled_warhead(); + new spell_z_check(); + new spell_warhead_detonate(); + new spell_vehicle_warhead_fuse(); + new spell_warhead_fuse(); } diff --git a/src/server/scripts/Northrend/zone_icecrown.cpp b/src/server/scripts/Northrend/zone_icecrown.cpp index 1e020edd10a..3d801cc2fbb 100644 --- a/src/server/scripts/Northrend/zone_icecrown.cpp +++ b/src/server/scripts/Northrend/zone_icecrown.cpp @@ -712,7 +712,7 @@ enum BorrowedTechnologyAndVolatility SPELL_PING_BUNNY = 59375, SPELL_IMMOLATION = 54690, SPELL_EXPLOSION = 59335, - SPELL_RIDE = 56687, + SPELL_RIDE = 59319, // Points POINT_GRAB_DECOY = 1, diff --git a/src/server/scripts/Northrend/zone_sholazar_basin.cpp b/src/server/scripts/Northrend/zone_sholazar_basin.cpp index f2edccd99b5..41785f76d9a 100644 --- a/src/server/scripts/Northrend/zone_sholazar_basin.cpp +++ b/src/server/scripts/Northrend/zone_sholazar_basin.cpp @@ -253,7 +253,7 @@ public: case 1: Talk(SAY_WP_3); me->CastSpell(5918.33f, 5372.91f, -98.770f, SPELL_EXPLODE_CRYSTAL, true); - me->SummonGameObject(184743, 5918.33f, 5372.91f, -98.770f, 0, 0, 0, 0, 0, TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5918.33f, 5372.91f, -98.770f, 0, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 2: @@ -264,7 +264,7 @@ public: break; case 8: me->CastSpell(5887.37f, 5379.39f, -91.289f, SPELL_EXPLODE_CRYSTAL, true); - me->SummonGameObject(184743, 5887.37f, 5379.39f, -91.289f, 0, 0, 0, 0, 0, TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5887.37f, 5379.39f, -91.289f, 0, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 9: @@ -780,7 +780,7 @@ public: bird->KillSelf(); crunchy->GetMotionMaster()->MovePoint(0, bird->GetPositionX(), bird->GetPositionY(), - bird->GetMap()->GetWaterOrGroundLevel(bird->GetPositionX(), bird->GetPositionY(), bird->GetPositionZ())); + bird->GetMap()->GetWaterOrGroundLevel(bird->GetPhaseMask(), bird->GetPositionX(), bird->GetPositionY(), bird->GetPositionZ())); /// @todo Make crunchy perform emote eat when he reaches the bird break; diff --git a/src/server/scripts/Northrend/zone_storm_peaks.cpp b/src/server/scripts/Northrend/zone_storm_peaks.cpp index e5263a8630a..490c72c5cba 100644 --- a/src/server/scripts/Northrend/zone_storm_peaks.cpp +++ b/src/server/scripts/Northrend/zone_storm_peaks.cpp @@ -516,7 +516,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) voice->AI()->Talk(SAY_VOICE_1, player); } - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_1, 7860.273f, -1383.622f, 1538.302f, -1.658062f, 0, 0, -0.737277f, 0.6755905f, 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_1, 7860.273f, -1383.622f, 1538.302f, -1.658062f, G3D::Quat(0.f, 0.f, -0.737277f, 0.6755905f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_5, 6000); break; @@ -524,7 +524,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_2, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_2, 7875.67f, -1387.266f, 1538.323f, -2.373644f, 0, 0, -0.9271832f, 0.3746083f, 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_2, 7875.67f, -1387.266f, 1538.323f, -2.373644f, G3D::Quat(0.f, 0.f, -0.9271832f, 0.3746083f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_6, 6000); break; @@ -532,7 +532,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_3, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_3, 7879.212f, -1401.175f, 1538.279f, 2.967041f, 0, 0, 0.9961939f, 0.08716504f, 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_3, 7879.212f, -1401.175f, 1538.279f, 2.967041f, G3D::Quat(0.f, 0.f, 0.9961939f, 0.08716504f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_7, 6000); break; @@ -540,7 +540,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_4, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_4, 7868.944f, -1411.18f, 1538.213f, 2.111848f, 0, 0, 0.8703556f, 0.4924237f, 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_4, 7868.944f, -1411.18f, 1538.213f, 2.111848f, G3D::Quat(0.f, 0.f, 0.8703556f, 0.4924237f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_8, 6000); break; @@ -548,7 +548,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_5, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_5, 7855.11f, -1406.839f, 1538.42f, 1.151916f, 0, 0, 0.5446386f, 0.8386708f, 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_5, 7855.11f, -1406.839f, 1538.42f, 1.151916f, G3D::Quat(0.f, 0.f, 0.5446386f, 0.8386708f), 0)) objectGUID[objectCounter] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_9, 6000); break; diff --git a/src/server/scripts/OutdoorPvP/CMakeLists.txt b/src/server/scripts/OutdoorPvP/CMakeLists.txt deleted file mode 100644 index 91ce4ce4186..00000000000 --- a/src/server/scripts/OutdoorPvP/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - OutdoorPvP/OutdoorPvPTF.cpp - OutdoorPvP/OutdoorPvPSI.cpp - OutdoorPvP/OutdoorPvPSI.h - OutdoorPvP/OutdoorPvPZM.cpp - OutdoorPvP/OutdoorPvPNA.cpp - OutdoorPvP/OutdoorPvPHP.cpp - OutdoorPvP/OutdoorPvPTF.h - OutdoorPvP/OutdoorPvPEP.h - OutdoorPvP/OutdoorPvPEP.cpp - OutdoorPvP/OutdoorPvPHP.h - OutdoorPvP/OutdoorPvPZM.h - OutdoorPvP/OutdoorPvPNA.h -) - -message(" -> Prepared: Outdoor PVP Zones") diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.h b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.h index 71dbd139ea0..4fd608ccd1c 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.h @@ -96,9 +96,9 @@ class OPvPCapturePointHP : public OPvPCapturePoint public: OPvPCapturePointHP(OutdoorPvP* pvp, OutdoorPvPHPTowerType type); - void ChangeState(); + void ChangeState() override; - void FillInitialWorldStates(WorldPacket & data); + void FillInitialWorldStates(WorldPacket & data) override; private: OutdoorPvPHPTowerType m_TowerType; @@ -109,18 +109,18 @@ class OutdoorPvPHP : public OutdoorPvP public: OutdoorPvPHP(); - bool SetupOutdoorPvP(); + bool SetupOutdoorPvP() override; - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); + void HandlePlayerEnterZone(Player* player, uint32 zone) override; + void HandlePlayerLeaveZone(Player* player, uint32 zone) override; - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void FillInitialWorldStates(WorldPacket &data); + void FillInitialWorldStates(WorldPacket &data) override; - void SendRemoveWorldStates(Player* player); + void SendRemoveWorldStates(Player* player) override; - void HandleKillImpl(Player* player, Unit* killed); + void HandleKillImpl(Player* player, Unit* killed) override; uint32 GetAllianceTowersControlled() const; void SetAllianceTowersControlled(uint32 count); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.h b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.h index 4ed47c42206..80878828d44 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.h @@ -311,18 +311,18 @@ class OutdoorPvPNA : public OutdoorPvP public: OutdoorPvPNA(); - bool SetupOutdoorPvP(); + bool SetupOutdoorPvP() override; - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); + void HandlePlayerEnterZone(Player* player, uint32 zone) override; + void HandlePlayerLeaveZone(Player* player, uint32 zone) override; - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void FillInitialWorldStates(WorldPacket &data); + void FillInitialWorldStates(WorldPacket &data) override; - void SendRemoveWorldStates(Player* player); + void SendRemoveWorldStates(Player* player) override; - void HandleKillImpl(Player* player, Unit* killed); + void HandleKillImpl(Player* player, Unit* killed) override; private: OPvPCapturePointNA * m_obj; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp index a0b9351fb75..05ed405cc6e 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp @@ -163,7 +163,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), 0, 0, 0, 0, 100, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) { delete go; return true; @@ -192,7 +192,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetOrientation(), 0, 0, 0, 0, 100, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) { delete go; return true; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.h b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.h index f28fea926fc..fae2ea9738e 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.h @@ -56,22 +56,22 @@ class OutdoorPvPSI : public OutdoorPvP public: OutdoorPvPSI(); - bool SetupOutdoorPvP(); + bool SetupOutdoorPvP() override; - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); + void HandlePlayerEnterZone(Player* player, uint32 zone) override; + void HandlePlayerLeaveZone(Player* player, uint32 zone) override; - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void FillInitialWorldStates(WorldPacket &data); + void FillInitialWorldStates(WorldPacket &data) override; - void SendRemoveWorldStates(Player* player); + void SendRemoveWorldStates(Player* player) override; - bool HandleAreaTrigger(Player* player, uint32 trigger); + bool HandleAreaTrigger(Player* player, uint32 trigger) override; - bool HandleDropFlag(Player* player, uint32 spellId); + bool HandleDropFlag(Player* player, uint32 spellId) override; - bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go); + bool HandleCustomSpell(Player* player, uint32 spellId, GameObject* go) override; void UpdateWorldState(); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPScriptLoader.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPScriptLoader.cpp new file mode 100644 index 00000000000..ebf29910046 --- /dev/null +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPScriptLoader.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_outdoorpvp_ep(); +void AddSC_outdoorpvp_hp(); +void AddSC_outdoorpvp_na(); +void AddSC_outdoorpvp_si(); +void AddSC_outdoorpvp_tf(); +void AddSC_outdoorpvp_zm(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddOutdoorPvPScripts() +{ + AddSC_outdoorpvp_ep(); + AddSC_outdoorpvp_hp(); + AddSC_outdoorpvp_na(); + AddSC_outdoorpvp_si(); + AddSC_outdoorpvp_tf(); + AddSC_outdoorpvp_zm(); +} diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.h b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.h index 237fee3283b..ebbccfd63cb 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.h @@ -132,11 +132,11 @@ class OPvPCapturePointTF : public OPvPCapturePoint public: OPvPCapturePointTF(OutdoorPvP* pvp, OutdoorPvPTF_TowerType type); - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void ChangeState(); + void ChangeState() override; - void FillInitialWorldStates(WorldPacket & data); + void FillInitialWorldStates(WorldPacket & data) override; void UpdateTowerState(); @@ -151,16 +151,16 @@ class OutdoorPvPTF : public OutdoorPvP public: OutdoorPvPTF(); - bool SetupOutdoorPvP(); + bool SetupOutdoorPvP() override; - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); + void HandlePlayerEnterZone(Player* player, uint32 zone) override; + void HandlePlayerLeaveZone(Player* player, uint32 zone) override; - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void FillInitialWorldStates(WorldPacket &data); + void FillInitialWorldStates(WorldPacket &data) override; - void SendRemoveWorldStates(Player* player); + void SendRemoveWorldStates(Player* player) override; uint32 GetAllianceTowersControlled() const; void SetAllianceTowersControlled(uint32 count); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h index e71fbf79280..352e6f108ea 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h @@ -161,9 +161,9 @@ class OPvPCapturePointZM_Beacon : public OPvPCapturePoint public: OPvPCapturePointZM_Beacon(OutdoorPvP* pvp, ZM_BeaconType type); - void ChangeState(); + void ChangeState() override; - void FillInitialWorldStates(WorldPacket & data); + void FillInitialWorldStates(WorldPacket & data) override; void UpdateTowerState(); @@ -218,18 +218,18 @@ class OutdoorPvPZM : public OutdoorPvP public: OutdoorPvPZM(); - bool SetupOutdoorPvP(); + bool SetupOutdoorPvP() override; - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); + void HandlePlayerEnterZone(Player* player, uint32 zone) override; + void HandlePlayerLeaveZone(Player* player, uint32 zone) override; - bool Update(uint32 diff); + bool Update(uint32 diff) override; - void FillInitialWorldStates(WorldPacket &data); + void FillInitialWorldStates(WorldPacket &data) override; - void SendRemoveWorldStates(Player* player); + void SendRemoveWorldStates(Player* player) override; - void HandleKillImpl(Player* player, Unit* killed); + void HandleKillImpl(Player* player, Unit* killed) override; uint32 GetAllianceTowersControlled() const; void SetAllianceTowersControlled(uint32 count); diff --git a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp index 9c16379c9f1..236f5bac403 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp @@ -64,12 +64,11 @@ public: return GetInstanceAI<boss_gurtogg_bloodboilAI>(creature); } - struct boss_gurtogg_bloodboilAI : public ScriptedAI + struct boss_gurtogg_bloodboilAI : public BossAI { - boss_gurtogg_bloodboilAI(Creature* creature) : ScriptedAI(creature) + boss_gurtogg_bloodboilAI(Creature* creature) : BossAI(creature, DATA_GURTOGG_BLOODBOIL) { Initialize(); - instance = creature->GetInstanceScript(); } void Initialize() @@ -91,8 +90,6 @@ public: Phase1 = true; } - InstanceScript* instance; - ObjectGuid TargetGUID; float TargetThreat; @@ -112,8 +109,7 @@ public: void Reset() override { - instance->SetBossState(DATA_GURTOGG_BLOODBOIL, NOT_STARTED); - + _Reset(); Initialize(); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); @@ -122,9 +118,8 @@ public: void EnterCombat(Unit* /*who*/) override { - DoZoneInCombat(); Talk(SAY_AGGRO); - instance->SetBossState(DATA_GURTOGG_BLOODBOIL, IN_PROGRESS); + _EnterCombat(); } void KilledUnit(Unit* /*victim*/) override @@ -134,9 +129,8 @@ public: void JustDied(Unit* /*killer*/) override { - instance->SetBossState(DATA_GURTOGG_BLOODBOIL, DONE); - Talk(SAY_DEATH); + _JustDied(); } void RevertThreatOnTarget(ObjectGuid guid) diff --git a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp index 7902c585509..a63d984d849 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp @@ -473,12 +473,11 @@ class boss_illidan_stormrage : public CreatureScript public: boss_illidan_stormrage() : CreatureScript("boss_illidan_stormrage") { } - struct boss_illidan_stormrageAI : public ScriptedAI + struct boss_illidan_stormrageAI : public BossAI { - boss_illidan_stormrageAI(Creature* creature) : ScriptedAI(creature), Summons(me) + boss_illidan_stormrageAI(Creature* creature) : BossAI(creature, DATA_ILLIDAN_STORMRAGE) { Initialize(); - instance = creature->GetInstanceScript(); DoCast(me, SPELL_DUAL_WIELD, true); } @@ -519,7 +518,7 @@ public: EnterPhase(PHASE_FLIGHT_SEQUENCE); } } - Summons.Despawn(summon); + summons.Despawn(summon); } void MovementInform(uint32 /*MovementType*/, uint32 /*Data*/) override @@ -539,6 +538,7 @@ public: void EnterCombat(Unit* /*who*/) override { + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); me->setActive(true); DoZoneInCombat(); } @@ -561,10 +561,10 @@ public: { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - instance->SetBossState(DATA_ILLIDAN_STORMRAGE, DONE); - for (uint8 i = DATA_GO_ILLIDAN_DOOR_R; i < DATA_GO_ILLIDAN_DOOR_L + 1; ++i) instance->HandleGameObject(instance->GetGuidData(i), true); + + _JustDied(); } void KilledUnit(Unit* victim) override @@ -585,7 +585,7 @@ public: void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override { - if (spell->Id == SPELL_GLAIVE_RETURNS) // Re-equip our warblades! + if (spell->Id == SPELL_GLAIVE_RETURNS) // Re-equip our warglaives! { if (!me->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID)) SetEquipmentSlots(false, EQUIP_ID_MAIN_HAND, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); @@ -673,7 +673,7 @@ public: Timer[EVENT_TALK_SEQUENCE] = 100; me->RemoveAllAuras(); me->InterruptNonMeleeSpells(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->GetMotionMaster()->Clear(false); me->AttackStop(); break; @@ -745,7 +745,7 @@ public: if (!Trigger) return; - Trigger->SetSpeed(MOVE_WALK, 3); + Trigger->SetSpeedRate(MOVE_WALK, 3); Trigger->SetWalk(true); Trigger->GetMotionMaster()->MovePoint(0, final.x, final.y, final.z); @@ -791,99 +791,99 @@ public: { switch (FlightCount) { - case 1: // lift off - me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); - me->SetDisableGravity(true); - me->StopMoving(); - Talk(SAY_ILLIDAN_TAKEOFF); - Timer[EVENT_FLIGHT_SEQUENCE] = 3000; - break; - case 2: // move to center - me->GetMotionMaster()->MovePoint(0, CENTER_X + 5, CENTER_Y, CENTER_Z); // +5, for SPELL_THROW_GLAIVE bug - Timer[EVENT_FLIGHT_SEQUENCE] = 0; - break; - case 3: // throw one glaive - { - uint8 i=1; - Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); - if (Glaive) + case 1: // lift off + me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF); + me->SetDisableGravity(true); + me->StopMoving(); + Talk(SAY_ILLIDAN_TAKEOFF); + Timer[EVENT_FLIGHT_SEQUENCE] = 3000; + break; + case 2: // move to center + me->GetMotionMaster()->MovePoint(0, CENTER_X + 5, CENTER_Y, CENTER_Z); // +5, for SPELL_THROW_GLAIVE bug + Timer[EVENT_FLIGHT_SEQUENCE] = 0; + break; + case 3: // throw one glaive { - GlaiveGUID[i] = Glaive->GetGUID(); - Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - Glaive->SetDisplayId(MODEL_INVISIBLE); - Glaive->setFaction(me->getFaction()); - DoCast(Glaive, SPELL_THROW_GLAIVE2); + uint8 i=1; + Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); + if (Glaive) + { + GlaiveGUID[i] = Glaive->GetGUID(); + Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + Glaive->SetDisplayId(MODEL_INVISIBLE); + Glaive->setFaction(me->getFaction()); + DoCast(Glaive, SPELL_THROW_GLAIVE2); + } } - } - Timer[EVENT_FLIGHT_SEQUENCE] = 700; - break; - case 4: // throw another - SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); - { - uint8 i=0; - Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); - if (Glaive) + Timer[EVENT_FLIGHT_SEQUENCE] = 700; + break; + case 4: // throw another + SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); { - GlaiveGUID[i] = Glaive->GetGUID(); - Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - Glaive->SetDisplayId(MODEL_INVISIBLE); - Glaive->setFaction(me->getFaction()); - DoCast(Glaive, SPELL_THROW_GLAIVE, true); + uint8 i=0; + Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0); + if (Glaive) + { + GlaiveGUID[i] = Glaive->GetGUID(); + Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + Glaive->SetDisplayId(MODEL_INVISIBLE); + Glaive->setFaction(me->getFaction()); + DoCast(Glaive, SPELL_THROW_GLAIVE, true); + } } - } - Timer[EVENT_FLIGHT_SEQUENCE] = 5000; - break; - case 5: // summon flames - SummonFlamesOfAzzinoth(); - Timer[EVENT_FLIGHT_SEQUENCE] = 3000; - break; - case 6: // fly to hover point - me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z); - Timer[EVENT_FLIGHT_SEQUENCE] = 0; - break; - case 7: // return to center - me->GetMotionMaster()->MovePoint(0, CENTER_X, CENTER_Y, CENTER_Z); - Timer[EVENT_FLIGHT_SEQUENCE] = 0; - break; - case 8: // glaive return - for (uint8 i = 0; i < 2; ++i) - { - if (GlaiveGUID[i]) + Timer[EVENT_FLIGHT_SEQUENCE] = 5000; + break; + case 5: // summon flames + SummonFlamesOfAzzinoth(); + Timer[EVENT_FLIGHT_SEQUENCE] = 3000; + break; + case 6: // fly to hover point + me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z); + Timer[EVENT_FLIGHT_SEQUENCE] = 0; + break; + case 7: // return to center + me->GetMotionMaster()->MovePoint(0, CENTER_X, CENTER_Y, CENTER_Z); + Timer[EVENT_FLIGHT_SEQUENCE] = 0; + break; + case 8: // glaive return + for (uint8 i = 0; i < 2; ++i) { - Unit* Glaive = ObjectAccessor::GetUnit(*me, GlaiveGUID[i]); - if (Glaive) + if (GlaiveGUID[i]) { - Glaive->CastSpell(me, SPELL_GLAIVE_RETURNS, false); // Make it look like the Glaive flies back up to us - Glaive->SetDisplayId(MODEL_INVISIBLE); // disappear but not die for now + Unit* Glaive = ObjectAccessor::GetUnit(*me, GlaiveGUID[i]); + if (Glaive) + { + Glaive->CastSpell(me, SPELL_GLAIVE_RETURNS, false); // Make it look like the Glaive flies back up to us + Glaive->SetDisplayId(MODEL_INVISIBLE); // disappear but not die for now + } } } - } - Timer[EVENT_FLIGHT_SEQUENCE] = 2000; - break; - case 9: // land - me->SetDisableGravity(false); - me->StopMoving(); - me->HandleEmoteCommand(EMOTE_ONESHOT_LAND); - for (uint8 i = 0; i < 2; ++i) - { - if (GlaiveGUID[i]) + Timer[EVENT_FLIGHT_SEQUENCE] = 2000; + break; + case 9: // land + me->SetDisableGravity(false); + me->StopMoving(); + me->HandleEmoteCommand(EMOTE_ONESHOT_LAND); + for (uint8 i = 0; i < 2; ++i) { - if (Creature* glaive = ObjectAccessor::GetCreature(*me, GlaiveGUID[i])) - glaive->DespawnOrUnsummon(); + if (GlaiveGUID[i]) + { + if (Creature* glaive = ObjectAccessor::GetCreature(*me, GlaiveGUID[i])) + glaive->DespawnOrUnsummon(); - GlaiveGUID[i].Clear(); + GlaiveGUID[i].Clear(); + } } - } - Timer[EVENT_FLIGHT_SEQUENCE] = 2000; - break; - case 10: // attack - DoResetThreat(); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE); - me->SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE); - EnterPhase(PHASE_NORMAL_2); - break; - default: - break; + Timer[EVENT_FLIGHT_SEQUENCE] = 2000; + break; + case 10: // attack + DoResetThreat(); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE); + me->SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE); + EnterPhase(PHASE_NORMAL_2); + break; + default: + break; } ++FlightCount; } @@ -913,23 +913,23 @@ public: switch (TransformCount) { - case 2: - DoResetThreat(); - break; - case 4: - EnterPhase(PHASE_DEMON); - break; - case 7: - DoResetThreat(); - break; - case 9: - if (MaievGUID) - EnterPhase(PHASE_NORMAL_MAIEV); // Depending on whether we summoned Maiev, we switch to either phase 5 or 3 - else - EnterPhase(PHASE_NORMAL_2); - break; - default: - break; + case 2: + DoResetThreat(); + break; + case 4: + EnterPhase(PHASE_DEMON); + break; + case 7: + DoResetThreat(); + break; + case 9: + if (MaievGUID) + EnterPhase(PHASE_NORMAL_MAIEV); // Depending on whether we summoned Maiev, we switch to either phase 5 or 3 + else + EnterPhase(PHASE_NORMAL_2); + break; + default: + break; } if (Phase == PHASE_TRANSFORM_SEQUENCE) Timer[EVENT_TRANSFORM_SEQUENCE] = DemonTransformation[TransformCount].timer; @@ -957,37 +957,37 @@ public: switch (Phase) { - case PHASE_NORMAL: - if (HealthBelowPct(65)) - EnterPhase(PHASE_FLIGHT_SEQUENCE); - break; + case PHASE_NORMAL: + if (HealthBelowPct(65)) + EnterPhase(PHASE_FLIGHT_SEQUENCE); + break; - case PHASE_NORMAL_2: - if (HealthBelowPct(30)) - EnterPhase(PHASE_TALK_SEQUENCE); - break; + case PHASE_NORMAL_2: + if (HealthBelowPct(30)) + EnterPhase(PHASE_TALK_SEQUENCE); + break; - case PHASE_NORMAL_MAIEV: - if (HealthBelowPct(1)) - EnterPhase(PHASE_TALK_SEQUENCE); - break; + case PHASE_NORMAL_MAIEV: + if (HealthBelowPct(1)) + EnterPhase(PHASE_TALK_SEQUENCE); + break; - case PHASE_TALK_SEQUENCE: - if (Event == EVENT_TALK_SEQUENCE) - HandleTalkSequence(); - break; + case PHASE_TALK_SEQUENCE: + if (Event == EVENT_TALK_SEQUENCE) + HandleTalkSequence(); + break; - case PHASE_FLIGHT_SEQUENCE: - if (Event == EVENT_FLIGHT_SEQUENCE) - HandleFlightSequence(); - break; + case PHASE_FLIGHT_SEQUENCE: + if (Event == EVENT_FLIGHT_SEQUENCE) + HandleFlightSequence(); + break; - case PHASE_TRANSFORM_SEQUENCE: - if (Event == EVENT_TRANSFORM_SEQUENCE) - HandleTransformSequence(); - break; - default: - break; + case PHASE_TRANSFORM_SEQUENCE: + if (Event == EVENT_TRANSFORM_SEQUENCE) + HandleTransformSequence(); + break; + default: + break; } if (me->IsNonMeleeSpellCast(false)) @@ -998,63 +998,63 @@ public: switch (Event) { // PHASE_NORMAL - case EVENT_BERSERK: - Talk(SAY_ILLIDAN_ENRAGE); - DoCast(me, SPELL_BERSERK, true); - Timer[EVENT_BERSERK] = 5000; // The buff actually lasts forever. - break; - - case EVENT_TAUNT: - Talk(SAY_ILLIDAN_TAUNT); - Timer[EVENT_TAUNT] = urand(25000, 35000); - break; - - case EVENT_SHEAR: - // no longer exists in 3.0f.2 - // DoCastVictim(SPELL_SHEAR); - Timer[EVENT_SHEAR] = 25000 + (rand32() % 16 * 1000); - break; - - case EVENT_FLAME_CRASH: - DoCastVictim(SPELL_FLAME_CRASH); - Timer[EVENT_FLAME_CRASH] = urand(30000, 40000); - break; - - case EVENT_PARASITIC_SHADOWFIEND: - { - if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true)) - DoCast(target, SPELL_PARASITIC_SHADOWFIEND, true); - Timer[EVENT_PARASITIC_SHADOWFIEND] = urand(35000, 45000); - } - break; - - case EVENT_PARASITE_CHECK: - Timer[EVENT_PARASITE_CHECK] = 0; - break; - - case EVENT_DRAW_SOUL: - DoCastVictim(SPELL_DRAW_SOUL); - Timer[EVENT_DRAW_SOUL] = urand(50000, 60000); - break; - - // PHASE_NORMAL_2 - case EVENT_AGONIZING_FLAMES: - DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_AGONIZING_FLAMES); - Timer[EVENT_AGONIZING_FLAMES] = 0; - break; - - case EVENT_TRANSFORM_NORMAL: - EnterPhase(PHASE_TRANSFORM_SEQUENCE); - break; - - // PHASE_NORMAL_MAIEV - case EVENT_ENRAGE: - DoCast(me, SPELL_ENRAGE); - Timer[EVENT_ENRAGE] = 0; - break; - - default: - break; + case EVENT_BERSERK: + Talk(SAY_ILLIDAN_ENRAGE); + DoCast(me, SPELL_BERSERK, true); + Timer[EVENT_BERSERK] = 5000; // The buff actually lasts forever. + break; + + case EVENT_TAUNT: + Talk(SAY_ILLIDAN_TAUNT); + Timer[EVENT_TAUNT] = urand(25000, 35000); + break; + + case EVENT_SHEAR: + // no longer exists in 3.0f.2 + // DoCastVictim(SPELL_SHEAR); + Timer[EVENT_SHEAR] = 25000 + (rand32() % 16 * 1000); + break; + + case EVENT_FLAME_CRASH: + DoCastVictim(SPELL_FLAME_CRASH); + Timer[EVENT_FLAME_CRASH] = urand(30000, 40000); + break; + + case EVENT_PARASITIC_SHADOWFIEND: + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true)) + DoCast(target, SPELL_PARASITIC_SHADOWFIEND, true); + Timer[EVENT_PARASITIC_SHADOWFIEND] = urand(35000, 45000); + } + break; + + case EVENT_PARASITE_CHECK: + Timer[EVENT_PARASITE_CHECK] = 0; + break; + + case EVENT_DRAW_SOUL: + DoCastVictim(SPELL_DRAW_SOUL); + Timer[EVENT_DRAW_SOUL] = urand(50000, 60000); + break; + + // PHASE_NORMAL_2 + case EVENT_AGONIZING_FLAMES: + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_AGONIZING_FLAMES); + Timer[EVENT_AGONIZING_FLAMES] = 0; + break; + + case EVENT_TRANSFORM_NORMAL: + EnterPhase(PHASE_TRANSFORM_SEQUENCE); + break; + + // PHASE_NORMAL_MAIEV + case EVENT_ENRAGE: + DoCast(me, SPELL_ENRAGE); + Timer[EVENT_ENRAGE] = 0; + break; + + default: + break; } DoMeleeAttackIfReady(); } @@ -1063,32 +1063,32 @@ public: { switch (Event) { - case EVENT_FIREBALL: - DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_FIREBALL); - Timer[EVENT_FIREBALL] = 3000; - break; - - case EVENT_DARK_BARRAGE: - DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_DARK_BARRAGE); - Timer[EVENT_DARK_BARRAGE] = 0; - break; - - case EVENT_EYE_BLAST: - CastEyeBlast(); - Timer[EVENT_EYE_BLAST] = 0; - break; - - case EVENT_MOVE_POINT: - Phase = PHASE_FLIGHT_SEQUENCE; - Timer[EVENT_FLIGHT_SEQUENCE] = 0; // do not start Event when changing hover point - HoverPoint += (rand32() % 3 + 1); - if (HoverPoint > 3) - HoverPoint -= 4; - me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z); - break; - - default: - break; + case EVENT_FIREBALL: + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_FIREBALL); + Timer[EVENT_FIREBALL] = 3000; + break; + + case EVENT_DARK_BARRAGE: + DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_DARK_BARRAGE); + Timer[EVENT_DARK_BARRAGE] = 0; + break; + + case EVENT_EYE_BLAST: + CastEyeBlast(); + Timer[EVENT_EYE_BLAST] = 0; + break; + + case EVENT_MOVE_POINT: + Phase = PHASE_FLIGHT_SEQUENCE; + Timer[EVENT_FLIGHT_SEQUENCE] = 0; // do not start Event when changing hover point + HoverPoint += (rand32() % 3 + 1); + if (HoverPoint > 3) + HoverPoint -= 4; + me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z); + break; + + default: + break; } } @@ -1096,29 +1096,29 @@ public: { switch (Event) { - case EVENT_SHADOW_BLAST: - me->GetMotionMaster()->Clear(false); - if (me->GetVictim() && (!me->IsWithinDistInMap(me->GetVictim(), 50) || !me->IsWithinLOSInMap(me->GetVictim()))) - me->GetMotionMaster()->MoveChase(me->GetVictim(), 30); - else - me->GetMotionMaster()->MoveIdle(); - DoCastVictim(SPELL_SHADOW_BLAST); - Timer[EVENT_SHADOW_BLAST] = 4000; - break; - case EVENT_SHADOWDEMON: - DoCast(me, SPELL_SUMMON_SHADOWDEMON); - Timer[EVENT_SHADOWDEMON] = 0; - Timer[EVENT_FLAME_BURST] += 10000; - break; - case EVENT_FLAME_BURST: - DoCast(me, SPELL_FLAME_BURST); - Timer[EVENT_FLAME_BURST] = 15000; - break; - case EVENT_TRANSFORM_DEMON: - EnterPhase(PHASE_TRANSFORM_SEQUENCE); - break; - default: - break; + case EVENT_SHADOW_BLAST: + me->GetMotionMaster()->Clear(false); + if (me->GetVictim() && (!me->IsWithinDistInMap(me->GetVictim(), 50) || !me->IsWithinLOSInMap(me->GetVictim()))) + me->GetMotionMaster()->MoveChase(me->GetVictim(), 30); + else + me->GetMotionMaster()->MoveIdle(); + DoCastVictim(SPELL_SHADOW_BLAST); + Timer[EVENT_SHADOW_BLAST] = 4000; + break; + case EVENT_SHADOWDEMON: + DoCast(me, SPELL_SUMMON_SHADOWDEMON); + Timer[EVENT_SHADOWDEMON] = 0; + Timer[EVENT_FLAME_BURST] += 10000; + break; + case EVENT_FLAME_BURST: + DoCast(me, SPELL_FLAME_BURST); + Timer[EVENT_FLAME_BURST] = 15000; + break; + case EVENT_TRANSFORM_DEMON: + EnterPhase(PHASE_TRANSFORM_SEQUENCE); + break; + default: + break; } } } @@ -1128,7 +1128,6 @@ public: uint32 Timer[EVENT_ENRAGE + 1]; PhaseIllidan Phase; private: - InstanceScript* instance; EventIllidan Event; uint32 TalkCount; uint32 TransformCount; @@ -1137,7 +1136,6 @@ public: ObjectGuid MaievGUID; ObjectGuid FlameGUID[2]; ObjectGuid GlaiveGUID[2]; - SummonList Summons; }; CreatureAI* GetAI(Creature* creature) const override @@ -1148,7 +1146,7 @@ public: /********************************** End of Illidan AI* *****************************************/ -/******* Functions and vars for Akama's AI* *****/ +/******* Functions and vars for Maiev's AI* *****/ class boss_maiev_shadowsong : public CreatureScript { public: @@ -1301,15 +1299,17 @@ public: EventMaiev Event = EVENT_MAIEV_NULL; for (uint8 i = 1; i <= MaxTimer; ++i) + { if (Timer[i]) { if (Timer[i] <= diff) Event = (EventMaiev)i; else Timer[i] -= diff; } + } - switch (Event) - { + switch (Event) + { case EVENT_MAIEV_STEALTH: { me->SetFullHealth(); @@ -1345,21 +1345,21 @@ public: break; default: break; - } + } - if (HealthBelowPct(50)) - { - me->SetVisible(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID)) - ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->DeleteFromThreatList(me->GetGUID()); - me->AttackStop(); - Timer[EVENT_MAIEV_STEALTH] = 60000; // reappear after 1 minute - MaxTimer = 1; - } + if (HealthBelowPct(50)) + { + me->SetVisible(false); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID)) + ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->DeleteFromThreatList(me->GetGUID()); + me->AttackStop(); + Timer[EVENT_MAIEV_STEALTH] = 60000; // reappear after 1 minute + MaxTimer = 1; + } - if (Phase == PHASE_NORMAL_MAIEV) - DoMeleeAttackIfReady(); + if (Phase == PHASE_NORMAL_MAIEV) + DoMeleeAttackIfReady(); } private: @@ -1375,6 +1375,7 @@ public: } }; +/******* Functions and vars for Akama's AI* *****/ class npc_akama_illidan : public CreatureScript { public: @@ -1432,7 +1433,7 @@ public: KillAllElites(); - me->SetUInt32Value(UNIT_NPC_FLAGS, 0); // Database sometimes has strange values.. + me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); // Database sometimes has strange values.. me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); me->setActive(false); me->SetVisible(false); @@ -1524,7 +1525,7 @@ public: void BeginWalk() { me->SetWalk(false); - me->SetSpeed(MOVE_RUN, 1.0f); + me->SetSpeedRate(MOVE_RUN, 1.0f); me->GetMotionMaster()->MovePoint(0, AkamaWP[WalkCount].x, AkamaWP[WalkCount].y, AkamaWP[WalkCount].z); } @@ -1809,7 +1810,7 @@ public: void boss_illidan_stormrage::boss_illidan_stormrageAI::Reset() { - instance->SetBossState(DATA_ILLIDAN_STORMRAGE, NOT_STARTED); + _Reset(); if (Creature* akama = ObjectAccessor::GetCreature(*me, AkamaGUID)) { @@ -1828,12 +1829,11 @@ void boss_illidan_stormrage::boss_illidan_stormrageAI::Reset() SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); me->SetDisableGravity(false); me->setActive(false); - Summons.DespawnAll(); } void boss_illidan_stormrage::boss_illidan_stormrageAI::JustSummoned(Creature* summon) { - Summons.Summon(summon); + summons.Summon(summon); switch (summon->GetEntry()) { case PARASITIC_SHADOWFIEND: @@ -1926,7 +1926,7 @@ void boss_illidan_stormrage::boss_illidan_stormrageAI::HandleTalkSequence() break; case 15: DoCast(me, SPELL_DEATH); // Animate his kneeling + stun him - Summons.DespawnAll(); + summons.DespawnAll(); break; case 17: if (Creature* akama = ObjectAccessor::GetCreature(*me, AkamaGUID)) diff --git a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp index aaf72512ae9..9412067f77e 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp @@ -149,7 +149,7 @@ public: void TeleportPlayers() { - uint32 random = urand(0, 7); + uint32 random = urand(0, 6); float X = TeleportPoint[random].x; float Y = TeleportPoint[random].y; float Z = TeleportPoint[random].z; @@ -210,7 +210,7 @@ public: break; case EVENT_PRISMATIC_SHIELD: // Random Prismatic Shield every 15 seconds. - DoCast(me, PrismaticAuras[urand(0, 6)]); + DoCast(me, PrismaticAuras[urand(0, 5)]); events.ScheduleEvent(EVENT_PRISMATIC_SHIELD, 15000); break; case EVENT_FATAL_ATTRACTION: diff --git a/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp b/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp index afc7d3d0fd7..d89437c2816 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp @@ -135,12 +135,11 @@ public: return GetInstanceAI<boss_reliquary_of_soulsAI>(creature); } - struct boss_reliquary_of_soulsAI : public ScriptedAI + struct boss_reliquary_of_soulsAI : public BossAI { - boss_reliquary_of_soulsAI(Creature* creature) : ScriptedAI(creature) + boss_reliquary_of_soulsAI(Creature* creature) : BossAI(creature, DATA_RELIQUARY_OF_SOULS) { Initialize(); - instance = creature->GetInstanceScript(); Counter = 0; Timer = 0; SoulCount = 0; @@ -152,8 +151,6 @@ public: Phase = 0; } - InstanceScript* instance; - ObjectGuid EssenceGUID; uint32 Phase; @@ -165,7 +162,7 @@ public: void Reset() override { - instance->SetBossState(DATA_RELIQUARY_OF_SOULS, NOT_STARTED); + _Reset(); if (EssenceGUID) { @@ -202,8 +199,7 @@ public: void EnterCombat(Unit* who) override { me->AddThreat(who, 10000.0f); - DoZoneInCombat(); - instance->SetBossState(DATA_RELIQUARY_OF_SOULS, IN_PROGRESS); + _EnterCombat(); Phase = 1; Counter = 0; @@ -246,11 +242,6 @@ public: } } - void JustDied(Unit* /*killer*/) override - { - instance->SetBossState(DATA_RELIQUARY_OF_SOULS, DONE); - } - void UpdateAI(uint32 diff) override { if (!Phase) diff --git a/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp b/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp index 7e1215488e1..c9e08176ad6 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp @@ -15,45 +15,45 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -/* -Name: Boss_Shade_of_Akama -%Complete: 80 -Comment: WIP A few more adds to script, ending script, and bugs. -Category: Black Temple -*/ - #include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "PassiveAI.h" #include "ScriptedGossip.h" #include "GridNotifiers.h" #include "black_temple.h" +#include "SpellScript.h" +#include "SpellAuraEffects.h" enum Says { - // Akama Ending cinematic text + // Akama SAY_BROKEN_FREE_0 = 0, SAY_BROKEN_FREE_1 = 1, - SAY_BROKEN_FREE_2 = 2 + SAY_BROKEN_FREE_2 = 2, + SAY_LOW_HEALTH = 3, + SAY_DEAD = 4, + // Ashtongue Broken + SAY_BROKEN_SPECIAL = 0, + SAY_BROKEN_HAIL = 1 }; enum Spells { // Akama - SPELL_STEALTH = 34189, // On Spawn - SPELL_AKAMA_SOUL_CHANNEL = 40447, // Cast on self hits Shade - SPELL_FIXATE = 40607, // Cast on self hits Shade - SPELL_CHAIN_LIGHTNING = 39945, // Combat - SPELL_DESTRUCTIVE_POISON = 40874, // Combat + SPELL_STEALTH = 34189, + SPELL_AKAMA_SOUL_CHANNEL = 40447, + SPELL_FIXATE = 40607, + SPELL_CHAIN_LIGHTNING = 39945, + SPELL_DESTRUCTIVE_POISON = 40874, + SPELL_AKAMA_SOUL_EXPEL = 40902, // Shade - SPELL_THREAT = 41602, // self cast hits Akama - SPELL_SHADE_OF_AKAMA_TRIGGER = 40955, // Cast on death - SPELL_AKAMA_SOUL_EXPEL_CHANNEL = 40927, // must hit shade - SPELL_AKAMA_SOUL_EXPEL = 40902, // the one he cast + SPELL_THREAT = 41602, + SPELL_SHADE_OF_AKAMA_TRIGGER = 40955, + SPELL_AKAMA_SOUL_EXPEL_CHANNEL = 40927, // Ashtongue Channeler SPELL_SHADE_SOUL_CHANNEL = 40401, SPELL_SHADE_SOUL_CHANNEL_2 = 40520, - SPELL_SHADOWFORM = 40973, // Cast on Shade // Creature Spawner SPELL_ASHTONGUE_WAVE_B = 42035, SPELL_SUMMON_ASHTONGUE_SORCERER = 40476, @@ -78,11 +78,6 @@ enum Spells enum Creatures { NPC_ASHTONGUE_CHANNELER = 23421, - NPC_ASHTONGUE_SORCERER = 23215, - NPC_ASHTONGUE_DEFENDER = 23216, - NPC_ASHTONGUE_ELEMENTALIST = 23523, - NPC_ASHTONGUE_ROGUE = 23318, - NPC_ASHTONGUE_SPIRITBINDER = 23524, NPC_ASHTONGUE_BROKEN = 23319, NPC_CREATURE_SPAWNER_AKAMA = 23210 }; @@ -95,60 +90,114 @@ enum Factions enum Actions { - ACTION_CHANNELER_DIED = 1, - ACTION_START_SPAWNING = 2, - ACTION_STOP_SPAWNING = 3, - ACTION_DESPAWN_ALL_SPAWNS = 4, + ACTION_START_SPAWNING = 0, + ACTION_STOP_SPAWNING = 1, + ACTION_DESPAWN_ALL_SPAWNS = 2, + ACTION_SHADE_OF_AKAMA_DEAD = 3, + ACTION_BROKEN_SPECIAL = 4, + ACTION_BROKEN_EMOTE = 5, + ACTION_BROKEN_HAIL = 6 }; enum Events { // Akama - EVENT_SHADE_START = 1, - EVENT_SHADE_CHANNEL = 2, - EVENT_FIXATE = 3, - EVENT_CHAIN_LIGHTNING = 4, - EVENT_DESTRUCTIVE_POISON = 5, - // Shade - EVENT_RESET_ENCOUNTER = 6, - EVENT_FIND_CHANNELERS_SPAWNERS = 7, - EVENT_SET_CHANNELERS_SPAWNERS = 8, - EVENT_START_ATTACK_AKAMA = 9, - EVENT_ADD_THREAT = 10, + EVENT_SHADE_START = 1, + EVENT_SHADE_CHANNEL = 2, + EVENT_FIXATE = 3, + EVENT_CHAIN_LIGHTNING = 4, + EVENT_DESTRUCTIVE_POISON = 5, + EVENT_START_BROKEN_FREE = 6, + EVENT_START_SOUL_EXPEL = 7, + EVENT_EVADE_CHECK = 8, + EVENT_BROKEN_FREE_1 = 9, + EVENT_BROKEN_FREE_2 = 10, + EVENT_BROKEN_FREE_3 = 11, + EVENT_BROKEN_FREE_4 = 12, + // Shade of Akama + EVENT_INITIALIZE_SPAWNERS = 13, + EVENT_START_CHANNELERS_AND_SPAWNERS = 14, + EVENT_ADD_THREAT = 15, // Creature spawner - EVENT_SPAWN_WAVE_B = 11, - EVENT_SUMMON_ASHTONGUE_SORCERER = 12, - EVENT_SUMMON_ASHTONGUE_DEFENDER = 13, - // Channeler - EVENT_CHANNEL = 14, - // Ashtongue Sorcerer - EVENT_SORCERER_CHANNEL = 15, + EVENT_SPAWN_WAVE_B = 16, + EVENT_SUMMON_ASHTONGUE_SORCERER = 17, + EVENT_SUMMON_ASHTONGUE_DEFENDER = 18, // Ashtongue Defender - EVENT_DEBILITATING_STRIKE = 16, - EVENT_HEROIC_STRIKE = 17, - EVENT_SHIELD_BASH = 18, - EVENT_WINDFURY = 29, + EVENT_DEBILITATING_STRIKE = 19, + EVENT_HEROIC_STRIKE = 20, + EVENT_SHIELD_BASH = 21, + EVENT_WINDFURY = 22, // Ashtongue Rogue - EVENT_DEBILITATING_POISON = 20, - EVENT_EVISCERATE = 21, + EVENT_DEBILITATING_POISON = 23, + EVENT_EVISCERATE = 24, // Ashtongue Elementalist - EVENT_RAIN_OF_FIRE = 22, - EVENT_LIGHTNING_BOLT = 23, + EVENT_RAIN_OF_FIRE = 25, + EVENT_LIGHTNING_BOLT = 26, // Ashtongue Spiritbinder - EVENT_SPIRIT_HEAL = 24 + EVENT_SPIRIT_HEAL = 27, + EVENT_SPIRIT_MEND_RESET = 28, + EVENT_CHAIN_HEAL_RESET = 29 }; -G3D::Vector3 const ShadeWP = { 512.4877f, 400.7993f, 112.7837f }; +enum Misc +{ + AKAMA_CHANNEL_WAYPOINT = 0, + AKAMA_INTRO_WAYPOINT = 1, + + SUMMON_GROUP_RESET = 1 +}; -G3D::Vector3 const AkamaWP[] = +Position const AkamaWP[2] = { { 517.4877f, 400.7993f, 112.7837f }, { 468.4435f, 401.1062f, 118.5379f } }; -// ######################################################## -// Shade of Akama -// ######################################################## +Position const BrokenPos[18] = +{ + { 495.5628f, 462.7089f, 112.8169f, 4.1808090f }, + { 498.3421f, 463.8384f, 112.8673f, 4.5634810f }, + { 501.6708f, 463.8806f, 112.8673f, 3.7157850f }, + { 532.4264f, 448.4718f, 112.8563f, 3.9813020f }, + { 532.9113f, 451.6227f, 112.8671f, 4.6479530f }, + { 532.8243f, 453.9475f, 112.8671f, 4.7032810f }, + { 521.5317f, 402.3790f, 112.8671f, 3.1138120f }, + { 521.9184f, 404.6848f, 112.8671f, 4.0787760f }, + { 522.4290f, 406.5160f, 112.8671f, 3.3869470f }, + { 521.0833f, 393.1852f, 112.8611f, 3.0750830f }, + { 521.9014f, 395.6381f, 112.8671f, 4.0157140f }, + { 522.2610f, 397.7423f, 112.8671f, 3.4417790f }, + { 532.4565f, 345.3987f, 112.8585f, 1.7232640f }, + { 532.5565f, 346.8792f, 112.8671f, 1.8325960f }, + { 532.5491f, 348.6840f, 112.8671f, 0.2054047f }, + { 501.4669f, 338.5967f, 112.8504f, 1.7038430f }, + { 499.0937f, 337.9894f, 112.8673f, 1.8586250f }, + { 496.8722f, 338.0152f, 112.8673f, 0.5428222f } +}; + +Position const BrokenWP[18] = +{ + { 479.1884f, 434.8635f, 112.7838f }, + { 479.7349f, 435.9843f, 112.7838f }, + { 480.5328f, 436.8310f, 112.7838f }, + { 493.1714f, 420.1136f, 112.7838f }, + { 494.7830f, 417.4830f, 112.7838f }, + { 492.9280f, 423.1891f, 112.7838f }, + { 491.8618f, 403.2035f, 112.7838f }, + { 491.7784f, 400.2046f, 112.7838f }, + { 491.9451f, 406.2023f, 112.7838f }, + { 488.3535f, 395.3652f, 112.7838f }, + { 488.8324f, 392.3267f, 112.7838f }, + { 489.2300f, 398.3135f, 112.7838f }, + { 491.9286f, 383.0433f, 112.7838f }, + { 491.1526f, 380.0966f, 112.7839f }, + { 493.6747f, 385.5407f, 112.7838f }, + { 476.2499f, 369.0865f, 112.7839f }, + { 473.7637f, 367.8766f, 112.7839f }, + { 478.8986f, 370.1895f, 112.7839f } +}; + +static float const MIDDLE_OF_ROOM = 400.0f; class boss_shade_of_akama : public CreatureScript { @@ -160,233 +209,144 @@ public: boss_shade_of_akamaAI(Creature* creature) : BossAI(creature, DATA_SHADE_OF_AKAMA) { Initialize(); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void Initialize() { - combatStarted = false; - akamaReached = false; - HasKilledAkama = false; - HasKilledAkamaAndReseting = false; + _spawners.clear(); + _isInPhaseOne = true; } void Reset() override { - _Reset(); - if (!HasKilledAkamaAndReseting) - { - for (GuidList::const_iterator itr = Channelers.begin(); itr != Channelers.end(); ++itr) - if (Creature* Channeler = ObjectAccessor::GetCreature(*me, *itr)) - Channeler->DespawnOrUnsummon(); - - for (GuidList::const_iterator itr = Spawners.begin(); itr != Spawners.end(); ++itr) - if (Creature* Spawner = ObjectAccessor::GetCreature(*me, *itr)) - Spawner->AI()->DoAction(ACTION_DESPAWN_ALL_SPAWNS); - - events.ScheduleEvent(EVENT_FIND_CHANNELERS_SPAWNERS, 3000); - events.ScheduleEvent(EVENT_RESET_ENCOUNTER, 5000); - } - + Initialize(); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); - + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_STUN); me->SetWalk(true); - Initialize(); + events.ScheduleEvent(EVENT_INITIALIZE_SPAWNERS, Seconds(1)); + me->SummonCreatureGroup(SUMMON_GROUP_RESET); } - void EnterCombat(Unit* /*who*/) override { } - - void AttackStart(Unit* who) override + void EnterEvadeMode(EvadeReason /*why*/) override { - if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) - { - if (Creature* Akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - if (Akama->IsAlive()) - ScriptedAI::AttackStart(Akama); - } - else - ScriptedAI::AttackStart(who); - } + _Reset(); - void DoAction(int32 actionId) override - { - if (actionId == ACTION_CHANNELER_DIED) - me->RemoveAuraFromStack(SPELL_SHADE_SOUL_CHANNEL_2); + for (ObjectGuid const& spawnerGuid : _spawners) + if (Creature* spawner = ObjectAccessor::GetCreature(*me, spawnerGuid)) + spawner->AI()->DoAction(ACTION_DESPAWN_ALL_SPAWNS); - UpdateSpeed(); + _DespawnAtEvade(); } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_AKAMA_SOUL_CHANNEL) { - combatStarted = true; - events.ScheduleEvent(EVENT_START_ATTACK_AKAMA, 500); - events.ScheduleEvent(EVENT_SET_CHANNELERS_SPAWNERS, 1000); + events.ScheduleEvent(EVENT_START_CHANNELERS_AND_SPAWNERS, Seconds(1)); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); - if (Creature* Akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - me->AddThreat(Akama, 10000000.0f); + events.ScheduleEvent(EVENT_EVADE_CHECK, Seconds(10)); + if (Creature* akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } - else if (spell->Id == SPELL_SHADE_SOUL_CHANNEL_2) - UpdateSpeed(); + + if (spell->Id == SPELL_AKAMA_SOUL_EXPEL) + DoCastSelf(SPELL_AKAMA_SOUL_EXPEL_CHANNEL); } - void UpdateSpeed() + void MovementInform(uint32 motionType, uint32 /*pointId*/) override { - float moveSpeed = 0.2f; - - if (me->GetAuraCount(SPELL_SHADE_SOUL_CHANNEL_2) <= 3) + if (_isInPhaseOne && motionType == CHASE_MOTION_TYPE) { - moveSpeed = (2.0f - (0.6f * me->GetAuraCount(SPELL_SHADE_SOUL_CHANNEL_2))); - me->SetSpeed(MOVE_WALK, moveSpeed / 2.5f); - me->SetSpeed(MOVE_RUN, (moveSpeed * 2) / 7); - me->ClearUnitState(UNIT_STATE_ROOT); + _isInPhaseOne = false; + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + me->SetWalk(false); + events.ScheduleEvent(EVENT_ADD_THREAT, Milliseconds(100)); + + for (ObjectGuid const& spawnerGuid : _spawners) + if (Creature* spawner = ObjectAccessor::GetCreature(*me, spawnerGuid)) + spawner->AI()->DoAction(ACTION_STOP_SPAWNING); } - else - me->AddUnitState(UNIT_STATE_ROOT); } - void UpdateAI(uint32 diff) override + void JustDied(Unit* /*killer*/) override { - if (HasKilledAkamaAndReseting) - return; + DoCastSelf(SPELL_SHADE_OF_AKAMA_TRIGGER); + + if (Creature* akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) + akama->AI()->DoAction(ACTION_SHADE_OF_AKAMA_DEAD); + for (ObjectGuid const& spawnerGuid : _spawners) + if (Creature* spawner = ObjectAccessor::GetCreature(*me, spawnerGuid)) + spawner->AI()->DoAction(ACTION_DESPAWN_ALL_SPAWNS); + + events.Reset(); + summons.DespawnEntry(NPC_ASHTONGUE_CHANNELER); + instance->SetBossState(DATA_SHADE_OF_AKAMA, DONE); + } + + void EnterEvadeModeIfNeeded() + { + Map::PlayerList const &players = me->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) + if (Player* player = i->GetSource()) + if (player->IsAlive() && !player->IsGameMaster() && CheckBoundary(player)) + return; + + EnterEvadeMode(EVADE_REASON_NO_HOSTILES); + } + + void UpdateAI(uint32 diff) override + { events.Update(diff); - if (!combatStarted) - { - while (uint32 eventId = events.ExecuteEvent()) - { - switch (eventId) - { - case EVENT_RESET_ENCOUNTER: - if (Creature* Akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - if (!Akama->IsAlive()) - Akama->Respawn(); - break; - case EVENT_FIND_CHANNELERS_SPAWNERS: - { - std::list<Creature*> ChannelerList; - me->GetCreatureListWithEntryInGrid(ChannelerList, NPC_ASHTONGUE_CHANNELER, 15.0f); - - if (!ChannelerList.empty()) - for (std::list<Creature*>::const_iterator itr = ChannelerList.begin(); itr != ChannelerList.end(); ++itr) - { - Channelers.push_back((*itr)->GetGUID()); - if ((*itr)->isDead()) - (*itr)->Respawn(); - } - - std::list<Creature*> SpawnerList; - me->GetCreatureListWithEntryInGrid(SpawnerList, NPC_CREATURE_SPAWNER_AKAMA, 90.0f); - - if (!SpawnerList.empty()) - for (std::list<Creature*>::const_iterator itr = SpawnerList.begin(); itr != SpawnerList.end(); ++itr) - Spawners.push_back((*itr)->GetGUID()); - - me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_STUN); - break; - } - default: - break; - } - } - } - else + if (!UpdateVictim()) + return; + + while (uint32 eventId = events.ExecuteEvent()) { - while (uint32 eventId = events.ExecuteEvent()) + switch (eventId) { - switch (eventId) + case EVENT_INITIALIZE_SPAWNERS: { - case EVENT_SET_CHANNELERS_SPAWNERS: - { - for (GuidList::const_iterator itr = Channelers.begin(); itr != Channelers.end(); ++itr) - if (Creature* Channeler = ObjectAccessor::GetCreature(*me, *itr)) - Channeler->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - - for (GuidList::const_iterator itr = Spawners.begin(); itr != Spawners.end(); ++itr) - if (Creature* Spawner = ObjectAccessor::GetCreature(*me, *itr)) - Spawner->AI()->DoAction(ACTION_START_SPAWNING); - break; - } - case EVENT_START_ATTACK_AKAMA: - me->GetMotionMaster()->MovePoint(0, ShadeWP.x, ShadeWP.y, ShadeWP.z, false); - events.ScheduleEvent(EVENT_START_ATTACK_AKAMA, 1000); - break; - case EVENT_ADD_THREAT: - DoCast(SPELL_THREAT); - events.ScheduleEvent(EVENT_ADD_THREAT, 3500); - break; - default: - break; - } - } + std::list<Creature*> SpawnerList; + me->GetCreatureListWithEntryInGrid(SpawnerList, NPC_CREATURE_SPAWNER_AKAMA); + for (Creature* spawner : SpawnerList) + _spawners.push_back(spawner->GetGUID()); - if (HasKilledAkama) - { - if (!HasKilledAkamaAndReseting) - { - HasKilledAkamaAndReseting = true; - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - instance->SetBossState(DATA_SHADE_OF_AKAMA, NOT_STARTED); - me->RemoveAllAurasExceptType(SPELL_AURA_DUMMY); - me->DeleteThreatList(); - me->CombatStop(); - me->GetMotionMaster()->MoveTargetedHome(); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); - combatStarted = false; - - if (Creature* Akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - Akama->DespawnOrUnsummon(); - - for (GuidList::const_iterator itr = Channelers.begin(); itr != Channelers.end(); ++itr) - if (Creature* Channeler = ObjectAccessor::GetCreature(*me, *itr)) - Channeler->DespawnOrUnsummon(); - - for (GuidList::const_iterator itr = Spawners.begin(); itr != Spawners.end(); ++itr) - if (Creature* Spawner = ObjectAccessor::GetCreature(*me, *itr)) - Spawner->AI()->DoAction(ACTION_DESPAWN_ALL_SPAWNS); - - events.ScheduleEvent(EVENT_FIND_CHANNELERS_SPAWNERS, 10000); - events.ScheduleEvent(EVENT_RESET_ENCOUNTER, 20000); + break; } - } - - if (!akamaReached) - { - if (Creature* Akama = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) + case EVENT_START_CHANNELERS_AND_SPAWNERS: { - if (me->IsWithinDist(Akama, 2.0f, false)) - { - akamaReached = true; - me->GetMotionMaster()->Clear(true); - me->GetMotionMaster()->MoveIdle(); - me->SetWalk(false); + for (ObjectGuid const& summonGuid : summons) + if (Creature* channeler = ObjectAccessor::GetCreature(*me, summonGuid)) + channeler->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + for (ObjectGuid const& spawnerGuid : _spawners) + if (Creature* spawner = ObjectAccessor::GetCreature(*me, spawnerGuid)) + spawner->AI()->DoAction(ACTION_START_SPAWNING); - events.CancelEvent(EVENT_START_ATTACK_AKAMA); - events.ScheduleEvent(EVENT_ADD_THREAT, 100); - - for (GuidList::const_iterator itr = Spawners.begin(); itr != Spawners.end(); ++itr) - if (Creature* Spawner = ObjectAccessor::GetCreature(*me, *itr)) - Spawner->AI()->DoAction(ACTION_STOP_SPAWNING); - } + break; } + case EVENT_ADD_THREAT: + DoCast(SPELL_THREAT); + events.Repeat(Seconds(3) + Milliseconds(500)); + break; + case EVENT_EVADE_CHECK: + EnterEvadeModeIfNeeded(); + events.Repeat(Seconds(10)); + break; + default: + break; } - else - DoMeleeAttackIfReady(); } + + DoMeleeAttackIfReady(); } - public: - bool HasKilledAkama; private: - GuidList Channelers; - GuidList Spawners; - bool akamaReached; - bool combatStarted; - bool HasKilledAkamaAndReseting; + GuidVector _spawners; + bool _isInPhaseOne; }; CreatureAI* GetAI(Creature* creature) const override @@ -395,10 +355,6 @@ public: } }; -// ######################################################## -// Akama -// ######################################################## - class npc_akama_shade : public CreatureScript { public: @@ -406,117 +362,188 @@ public: struct npc_akamaAI : public ScriptedAI { - npc_akamaAI(Creature* creature) : ScriptedAI(creature) + npc_akamaAI(Creature* creature) : ScriptedAI(creature), _summons(me) { Initialize(); - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Initialize() { - StartChannel = false; - StartCombat = false; - HasYelledOnce = false; - ShadeHasDied = false; + _isInCombat = false; + _hasYelledOnce = false; + _chosen.Clear(); + _summons.DespawnAll(); + _events.Reset(); } void Reset() override { - me->setFaction(FACTION_FRIENDLY); - DoCast(me, SPELL_STEALTH); Initialize(); + me->setFaction(FACTION_FRIENDLY); + DoCastSelf(SPELL_STEALTH); - if (instance->GetBossState(DATA_SHADE_OF_AKAMA) != DONE) + if (_instance->GetBossState(DATA_SHADE_OF_AKAMA) != DONE) me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); } - void JustDied(Unit* /*killer*/) override + void JustSummoned(Creature* summon) override { - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) - if (Shade->IsAlive()) - ENSURE_AI(boss_shade_of_akama::boss_shade_of_akamaAI, Shade->AI())->HasKilledAkama = true; - me->GetMotionMaster()->Clear(true); - me->GetMotionMaster()->MoveIdle(); + _summons.Summon(summon); } + void EnterEvadeMode(EvadeReason /*why*/) override { } + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { - if (spell->Id == SPELL_THREAT && !StartCombat) + if (spell->Id == SPELL_THREAT && !_isInCombat) { - me->ClearUnitState(UNIT_STATE_ROOT); - me->RemoveAura(SPELL_AKAMA_SOUL_CHANNEL); - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) - Shade->RemoveAura(SPELL_AKAMA_SOUL_CHANNEL); - StartCombat = true; + _isInCombat = true; + me->SetWalk(false); + me->RemoveAurasDueToSpell(SPELL_AKAMA_SOUL_CHANNEL); + if (Creature* shade = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + { + shade->RemoveAurasDueToSpell(SPELL_AKAMA_SOUL_CHANNEL); + AttackStart(shade); + _events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, Seconds(2)); + _events.ScheduleEvent(EVENT_DESTRUCTIVE_POISON, Seconds(5)); + } } } - void EnterCombat(Unit* /*who*/) override + void DamageTaken(Unit* /*who*/, uint32& /*damage*/) override { - events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, 2000); - events.ScheduleEvent(EVENT_DESTRUCTIVE_POISON, 5000); + if (me->HealthBelowPct(20) && !_hasYelledOnce) + { + _hasYelledOnce = true; + Talk(SAY_LOW_HEALTH); + } } - void UpdateAI(uint32 diff) override + void DoAction(int32 actionId) override { - if (StartChannel) + if (actionId == ACTION_SHADE_OF_AKAMA_DEAD) { - events.Update(diff); + _isInCombat = false; + me->CombatStop(true); + me->setFaction(FACTION_FRIENDLY); + me->SetWalk(true); + _events.Reset(); + me->GetMotionMaster()->MovePoint(AKAMA_INTRO_WAYPOINT, AkamaWP[1]); + } + } - while (uint32 eventId = events.ExecuteEvent()) + void MovementInform(uint32 motionType, uint32 pointId) override + { + if (motionType != POINT_MOTION_TYPE) + return; + + if (pointId == AKAMA_CHANNEL_WAYPOINT) + _events.ScheduleEvent(EVENT_SHADE_CHANNEL, Seconds(1)); + + else if (pointId == AKAMA_INTRO_WAYPOINT) + { + me->SetWalk(false); + me->SetFacingTo(0.08726646f); + _events.ScheduleEvent(EVENT_START_SOUL_EXPEL, Seconds(1)); + } + } + + void SummonBrokens() + { + for (uint8 i = 0; i < 18; i++) + { + if (TempSummon* summoned = me->SummonCreature(NPC_ASHTONGUE_BROKEN, BrokenPos[i])) { - switch (eventId) - { - case EVENT_SHADE_START: - instance->SetBossState(DATA_SHADE_OF_AKAMA, IN_PROGRESS); - me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - me->RemoveAura(SPELL_STEALTH); - me->SetWalk(true); - me->GetMotionMaster()->MovePoint(0, AkamaWP[0].x, AkamaWP[0].y, AkamaWP[0].z, false); - events.ScheduleEvent(EVENT_SHADE_CHANNEL, 10000); - break; - case EVENT_SHADE_CHANNEL: - me->AddUnitState(UNIT_STATE_ROOT); - me->SetFacingTo(3.118662f); - DoCast(me, SPELL_AKAMA_SOUL_CHANNEL); - me->setFaction(FACTION_COMBAT); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); - events.ScheduleEvent(EVENT_FIXATE, 5000); - break; - case EVENT_FIXATE: - DoCast(SPELL_FIXATE); - StartChannel = false; - break; - default: - break; - } + summoned->SetWalk(true); + summoned->GetMotionMaster()->MovePoint(0, BrokenWP[i]); + if (i == 9) //On Sniffs, npc that Yell "Special" is the tenth to be created + _chosen = summoned->GetGUID(); } } + } - if (!UpdateVictim()) - return; - - events.Update(diff); + void UpdateAI(uint32 diff) override + { + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { + case EVENT_SHADE_START: + _instance->SetBossState(DATA_SHADE_OF_AKAMA, IN_PROGRESS); + me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); + me->RemoveAurasDueToSpell(SPELL_STEALTH); + me->SetWalk(true); + me->GetMotionMaster()->MovePoint(AKAMA_CHANNEL_WAYPOINT, AkamaWP[0], false); + break; + case EVENT_SHADE_CHANNEL: + me->SetFacingTo(3.118662f); + DoCastSelf(SPELL_AKAMA_SOUL_CHANNEL); + me->setFaction(FACTION_COMBAT); + _events.ScheduleEvent(EVENT_FIXATE, Seconds(5)); + break; + case EVENT_FIXATE: + DoCast(SPELL_FIXATE); + break; case EVENT_CHAIN_LIGHTNING: DoCastVictim(SPELL_CHAIN_LIGHTNING); - events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, urand(10000, 15000)); + _events.Repeat(randtime(Seconds(8), Seconds(15))); break; case EVENT_DESTRUCTIVE_POISON: - DoCast(me, SPELL_DESTRUCTIVE_POISON); - events.ScheduleEvent(EVENT_DESTRUCTIVE_POISON, urand(4000, 5000)); + DoCastSelf(SPELL_DESTRUCTIVE_POISON); + _events.Repeat(randtime(Seconds(3), Seconds(7))); + break; + case EVENT_START_SOUL_EXPEL: + DoCast(SPELL_AKAMA_SOUL_EXPEL); + _events.ScheduleEvent(EVENT_START_BROKEN_FREE, Seconds(15)); + break; + case EVENT_START_BROKEN_FREE: + me->HandleEmoteCommand(EMOTE_ONESHOT_ROAR); + Talk(SAY_BROKEN_FREE_0); + SummonBrokens(); + _events.ScheduleEvent(EVENT_BROKEN_FREE_1, Seconds(10)); + break; + case EVENT_BROKEN_FREE_1: + Talk(SAY_BROKEN_FREE_1); + _events.ScheduleEvent(EVENT_BROKEN_FREE_2, Seconds(12)); + break; + case EVENT_BROKEN_FREE_2: + Talk(SAY_BROKEN_FREE_2); + _events.ScheduleEvent(EVENT_BROKEN_FREE_3, Seconds(15)); + break; + case EVENT_BROKEN_FREE_3: + if (Creature* special = ObjectAccessor::GetCreature(*me, _chosen)) + special->AI()->Talk(SAY_BROKEN_SPECIAL); + + _summons.DoAction(ACTION_BROKEN_EMOTE, _pred); + _events.ScheduleEvent(EVENT_BROKEN_FREE_4, Seconds(5)); + break; + case EVENT_BROKEN_FREE_4: + _summons.DoAction(ACTION_BROKEN_HAIL, _pred); break; default: break; } } - DoMeleeAttackIfReady(); + if (me->getFaction() == FACTION_COMBAT) + { + if (!UpdateVictim()) + return; + + DoMeleeAttackIfReady(); + } + } + + void JustDied(Unit* /*killer*/) override + { + _summons.DespawnAll(); + Talk(SAY_DEAD); + if (Creature* shade = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + if (shade->IsAlive()) + shade->AI()->EnterEvadeMode(EVADE_REASON_OTHER); } void sGossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override @@ -524,19 +551,18 @@ public: if (gossipListId == 0) { player->CLOSE_GOSSIP_MENU(); - StartChannel = true; - events.ScheduleEvent(EVENT_SHADE_START, 500); + _events.ScheduleEvent(EVENT_SHADE_START, Milliseconds(500)); } } private: - InstanceScript* instance; - EventMap events; - bool StartChannel; - bool ShadeHasDied; - bool StartCombat; - bool HasYelledOnce; - + InstanceScript* _instance; + EventMap _events; + SummonList _summons; + DummyEntryCheckPredicate _pred; + ObjectGuid _chosen; //Creature that should yell the speech special. + bool _isInCombat; + bool _hasYelledOnce; }; CreatureAI* GetAI(Creature* creature) const override @@ -545,70 +571,44 @@ public: } }; -// ######################################################## -// Ashtongue Channeler -// ######################################################## - class npc_ashtongue_channeler : public CreatureScript { public: npc_ashtongue_channeler() : CreatureScript("npc_ashtongue_channeler") { } - struct npc_ashtongue_channelerAI : public ScriptedAI + struct npc_ashtongue_channelerAI : public PassiveAI { - npc_ashtongue_channelerAI(Creature* creature) : ScriptedAI(creature) + npc_ashtongue_channelerAI(Creature* creature) : PassiveAI(creature) { - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Reset() override { - me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); - me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true); + _scheduler.Schedule(Seconds(2), [this](TaskContext channel) + { + if (Creature* shade = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + { + if (shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) + DoCastSelf(SPELL_SHADE_SOUL_CHANNEL); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - events.ScheduleEvent(EVENT_CHANNEL, 2000); - } + else + me->DespawnOrUnsummon(Seconds(3)); + } - void JustDied(Unit* /*killer*/) override - { - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) - Shade->AI()->DoAction(ACTION_CHANNELER_DIED); + channel.Repeat(Seconds(2)); + }); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } - void EnterCombat(Unit* /*who*/) override { } - void AttackStart(Unit* /*who*/) override { } - void UpdateAI(uint32 diff) override { - events.Update(diff); - - while (uint32 eventId = events.ExecuteEvent()) - { - switch (eventId) - { - case EVENT_CHANNEL: - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) - { - if (Shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) - DoCast(me, SPELL_SHADE_SOUL_CHANNEL); - else - { - me->InterruptSpell(CURRENT_CHANNELED_SPELL); - Shade->AI()->DoAction(ACTION_CHANNELER_DIED); - } - } - events.ScheduleEvent(EVENT_CHANNEL, 2000); - break; - default: - break; - } - } + _scheduler.Update(diff); } private: - InstanceScript* instance; - EventMap events; + InstanceScript* _instance; + TaskScheduler _scheduler; }; CreatureAI* GetAI(Creature* creature) const override @@ -617,10 +617,6 @@ public: } }; -// ######################################################## -// Creature Generator Akama -// ######################################################## - class npc_creature_generator_akama : public CreatureScript { public: @@ -628,57 +624,53 @@ public: struct npc_creature_generator_akamaAI : public ScriptedAI { - npc_creature_generator_akamaAI(Creature* creature) : ScriptedAI(creature), Summons(me) + npc_creature_generator_akamaAI(Creature* creature) : ScriptedAI(creature), _summons(me) { Initialize(); - instance = creature->GetInstanceScript(); } void Initialize() { - doSpawning = false; - leftSide = false; + _leftSide = false; + _events.Reset(); + _summons.DespawnAll(); } void Reset() override { - Summons.DespawnAll(); - Initialize(); - if (me->GetPositionY() < 400.0f) - leftSide = true; + if (me->GetPositionY() < MIDDLE_OF_ROOM) + _leftSide = true; } void JustSummoned(Creature* summon) override { - Summons.Summon(summon); + _summons.Summon(summon); } void DoAction(int32 actionId) override { - doSpawning = true; - switch (actionId) { case ACTION_START_SPAWNING: - if (leftSide) + if (_leftSide) { - events.ScheduleEvent(EVENT_SPAWN_WAVE_B, 100); - events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_SORCERER, urand(2000, 5000)); + _events.ScheduleEvent(EVENT_SPAWN_WAVE_B, Milliseconds(100)); + _events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_SORCERER, randtime(Seconds(2), Seconds(5))); } else { - events.ScheduleEvent(EVENT_SPAWN_WAVE_B, 10000); - events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_DEFENDER, urand(2000, 5000)); + _events.ScheduleEvent(EVENT_SPAWN_WAVE_B, Seconds(10)); + _events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_DEFENDER, randtime(Seconds(2), Seconds(5))); } break; case ACTION_STOP_SPAWNING: - doSpawning = false; + _events.Reset(); break; case ACTION_DESPAWN_ALL_SPAWNS: - doSpawning = false; - Summons.DespawnAll(); + _events.Reset(); + _summons.DespawnAll(); break; default: break; @@ -687,39 +679,34 @@ public: void UpdateAI(uint32 diff) override { - if (doSpawning) - { - events.Update(diff); + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) { - switch (eventId) - { - case EVENT_SPAWN_WAVE_B: - DoCast(me, SPELL_ASHTONGUE_WAVE_B); - events.ScheduleEvent(EVENT_SPAWN_WAVE_B, urand(45000, 50000)); - break; - case EVENT_SUMMON_ASHTONGUE_SORCERER: // left - DoCast(me, SPELL_SUMMON_ASHTONGUE_SORCERER); - events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_SORCERER, urand(30000, 35000)); - break; - case EVENT_SUMMON_ASHTONGUE_DEFENDER: // right - DoCast(me, SPELL_SUMMON_ASHTONGUE_DEFENDER); - events.ScheduleEvent(EVENT_SUMMON_ASHTONGUE_DEFENDER, urand(30000, 35000)); - break; - default: - break; - } + case EVENT_SPAWN_WAVE_B: + DoCastSelf(SPELL_ASHTONGUE_WAVE_B); + _events.Repeat(randtime(Seconds(50), Seconds(60))); + break; + case EVENT_SUMMON_ASHTONGUE_SORCERER: // left + DoCastSelf(SPELL_SUMMON_ASHTONGUE_SORCERER); + _events.Repeat(randtime(Seconds(30), Seconds(35))); + break; + case EVENT_SUMMON_ASHTONGUE_DEFENDER: // right + DoCastSelf(SPELL_SUMMON_ASHTONGUE_DEFENDER); + _events.Repeat(randtime(Seconds(30), Seconds(40))); + break; + default: + break; } } } private: - InstanceScript* instance; - EventMap events; - SummonList Summons; - bool leftSide; - bool doSpawning; + EventMap _events; + SummonList _summons; + bool _leftSide; }; CreatureAI* GetAI(Creature* creature) const override @@ -728,10 +715,6 @@ public: } }; -// ######################################################## -// Ashtongue Sorcerer -// ######################################################## - class npc_ashtongue_sorcerer : public CreatureScript { public: @@ -742,103 +725,96 @@ public: npc_ashtongue_sorcererAI(Creature* creature) : ScriptedAI(creature) { Initialize(); - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Initialize() { - startedBanishing = false; - switchToCombat = false; + _switchToCombat = false; + _inBanish = false; } void Reset() override { - if (!startedBanishing) + if (Creature* shade = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_SHADE_OF_AKAMA))) { - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + if (shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) + me->GetMotionMaster()->MovePoint(0, shade->GetPosition()); + + else { - if (Shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) - me->GetMotionMaster()->MovePoint(0, Shade->GetPositionX(), Shade->GetPositionY(), Shade->GetPositionZ(), false); - else - { - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); - } + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } } - Initialize(); } void JustDied(Unit* /*killer*/) override { - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) - Shade->AI()->DoAction(ACTION_CHANNELER_DIED); - me->DespawnOrUnsummon(5000); + me->DespawnOrUnsummon(Seconds(5)); } + void EnterEvadeMode(EvadeReason /*why*/) override { } void EnterCombat(Unit* /*who*/) override { } void AttackStart(Unit* who) override { - if (!switchToCombat) + if (!_switchToCombat) return; + ScriptedAI::AttackStart(who); } - void UpdateAI(uint32 diff) override + void MoveInLineOfSight(Unit* who) override { - events.Update(diff); - - while (uint32 eventId = events.ExecuteEvent()) + if (!_inBanish && who->GetGUID() == _instance->GetGuidData(DATA_SHADE_OF_AKAMA) && me->IsWithinDist(who, 20.0f, false)) { - switch (eventId) + _inBanish = true; + me->StopMoving(); + me->GetMotionMaster()->Clear(false); + me->GetMotionMaster()->MovePoint(1, me->GetPositionX() + frand(-8.0f, 8.0f), me->GetPositionY() + frand(-8.0f, 8.0f), me->GetPositionZ()); + + _scheduler.Schedule(Seconds(1) + Milliseconds(500), [this](TaskContext sorcer_channel) { - case EVENT_SORCERER_CHANNEL: - if (Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + if (Creature* shade = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_SHADE_OF_AKAMA))) + { + if (shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) { - if (Shade->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) - { - me->SetFacingToObject(Shade); - DoCast(me, SPELL_SHADE_SOUL_CHANNEL); - events.ScheduleEvent(EVENT_SORCERER_CHANNEL, 2000); - } - else - { - me->InterruptSpell(CURRENT_CHANNELED_SPELL); - Shade->AI()->DoAction(ACTION_CHANNELER_DIED); - switchToCombat = true; - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); - } + me->SetFacingToObject(shade); + DoCastSelf(SPELL_SHADE_SOUL_CHANNEL); + sorcer_channel.Repeat(Seconds(2)); } - break; - default: - break; - } + else + { + me->InterruptSpell(CURRENT_CHANNELED_SPELL); + _switchToCombat = true; + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); + } + } + }); } + } - if (!startedBanishing) - { - Creature* Shade = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_SHADE_OF_AKAMA)); - if (me->IsWithinDist(Shade, 20.0f, false)) - { - me->StopMoving(); - me->GetMotionMaster()->Clear(false); - me->GetMotionMaster()->MovePoint(1, me->GetPositionX() + frand (-8.0f, 8.0f), me->GetPositionY() + frand (-8.0f, 8.0f), me->GetPositionZ(), false); - events.ScheduleEvent(EVENT_SORCERER_CHANNEL, 1500); - startedBanishing = true; - } - } + void UpdateAI(uint32 diff) override + { + _scheduler.Update(diff); + + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + if (!UpdateVictim()) + return; DoMeleeAttackIfReady(); } private: - InstanceScript* instance; - EventMap events; - bool startedBanishing; - bool switchToCombat; + InstanceScript* _instance; + TaskScheduler _scheduler; + bool _switchToCombat; + bool _inBanish; }; CreatureAI* GetAI(Creature* creature) const override @@ -847,10 +823,6 @@ public: } }; -// ######################################################## -// Ashtongue Defender -// ######################################################## - class npc_ashtongue_defender : public CreatureScript { public: @@ -860,54 +832,55 @@ public: { npc_ashtongue_defenderAI(Creature* creature) : ScriptedAI(creature) { - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Reset() override { - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } void JustDied(Unit* /*killer*/) override { - me->DespawnOrUnsummon(5000); + me->DespawnOrUnsummon(Seconds(5)); } void EnterCombat(Unit* /*who*/) override { - events.ScheduleEvent(EVENT_HEROIC_STRIKE, 5000); - events.ScheduleEvent(EVENT_SHIELD_BASH, urand(10000, 16000)); - events.ScheduleEvent(EVENT_DEBILITATING_STRIKE, urand(10000, 16000)); - events.ScheduleEvent(EVENT_WINDFURY, urand(8000, 12000)); + _events.ScheduleEvent(EVENT_HEROIC_STRIKE, Seconds(5)); + _events.ScheduleEvent(EVENT_SHIELD_BASH, randtime(Seconds(10), Seconds(16))); + _events.ScheduleEvent(EVENT_DEBILITATING_STRIKE, randtime(Seconds(10), Seconds(16))); + _events.ScheduleEvent(EVENT_WINDFURY, randtime(Seconds(8), Seconds(12))); } + void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; - events.Update(diff); + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_DEBILITATING_STRIKE: DoCastVictim(SPELL_DEBILITATING_STRIKE); - events.ScheduleEvent(EVENT_DEBILITATING_STRIKE, urand(8000, 16000)); + _events.Repeat(randtime(Seconds(20), Seconds(25))); break; case EVENT_HEROIC_STRIKE: - DoCast(me, SPELL_HEROIC_STRIKE); - events.ScheduleEvent(EVENT_HEROIC_STRIKE, urand(50000, 60000)); + DoCastSelf(SPELL_HEROIC_STRIKE); + _events.Repeat(randtime(Seconds(5), Seconds(15))); break; case EVENT_SHIELD_BASH: DoCastVictim(SPELL_SHIELD_BASH); - events.ScheduleEvent(EVENT_SHIELD_BASH, urand(8000, 16000)); + _events.Repeat(randtime(Seconds(10), Seconds(20))); break; case EVENT_WINDFURY: DoCastVictim(SPELL_WINDFURY); - events.ScheduleEvent(EVENT_WINDFURY, urand(6000 , 8000)); + _events.Repeat(randtime(Seconds(6), Seconds(8))); break; default: break; @@ -918,8 +891,8 @@ public: } private: - InstanceScript* instance; - EventMap events; + InstanceScript* _instance; + EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override @@ -928,10 +901,6 @@ public: } }; -// ######################################################## -// Ashtongue Rogue -// ######################################################## - class npc_ashtongue_rogue : public CreatureScript { public: @@ -941,44 +910,46 @@ public: { npc_ashtongue_rogueAI(Creature* creature) : ScriptedAI(creature) { - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Reset() override { - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } void JustDied(Unit* /*killer*/) override { - me->DespawnOrUnsummon(5000); + me->DespawnOrUnsummon(Seconds(5)); } void EnterCombat(Unit* /*who*/) override { - events.ScheduleEvent(EVENT_DEBILITATING_POISON, urand(500, 2000)); - events.ScheduleEvent(EVENT_EVISCERATE, urand(2000, 5000)); + _events.ScheduleEvent(EVENT_DEBILITATING_POISON, randtime(Milliseconds(500), Seconds(2))); + _events.ScheduleEvent(EVENT_EVISCERATE, randtime(Seconds(2), Seconds(5))); } + void EnterEvadeMode(EvadeReason /*why*/) override { } + void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; - events.Update(diff); + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_DEBILITATING_POISON: DoCastVictim(SPELL_DEBILITATING_POISON); - events.ScheduleEvent(EVENT_DEBILITATING_POISON, urand(14000, 18000)); + _events.Repeat(randtime(Seconds(15), Seconds(20))); break; case EVENT_EVISCERATE: DoCastVictim(SPELL_EVISCERATE); - events.ScheduleEvent(EVENT_EVISCERATE, urand(12000, 16000)); + _events.Repeat(randtime(Seconds(12), Seconds(20))); break; default: break; @@ -989,8 +960,8 @@ public: } private: - InstanceScript* instance; - EventMap events; + InstanceScript* _instance; + EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override @@ -999,10 +970,6 @@ public: } }; -// ######################################################## -// Ashtongue Elementalist -// ######################################################## - class npc_ashtongue_elementalist : public CreatureScript { public: @@ -1012,44 +979,46 @@ public: { npc_ashtongue_elementalistAI(Creature* creature) : ScriptedAI(creature) { - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Reset() override { - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } void JustDied(Unit* /*killer*/) override { - me->DespawnOrUnsummon(5000); + me->DespawnOrUnsummon(Seconds(5)); } void EnterCombat(Unit* /*who*/) override { - events.ScheduleEvent(EVENT_RAIN_OF_FIRE, 18000); - events.ScheduleEvent(EVENT_LIGHTNING_BOLT, 6000); + _events.ScheduleEvent(EVENT_RAIN_OF_FIRE, Seconds(18)); + _events.ScheduleEvent(EVENT_LIGHTNING_BOLT, Seconds(6)); } + void EnterEvadeMode(EvadeReason /*why*/) override { } + void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; - events.Update(diff); + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_RAIN_OF_FIRE: DoCastVictim(SPELL_RAIN_OF_FIRE); - events.ScheduleEvent(EVENT_RAIN_OF_FIRE, 20000); + _events.Repeat(randtime(Seconds(15), Seconds(20))); break; case EVENT_LIGHTNING_BOLT: DoCastVictim(SPELL_LIGHTNING_BOLT); - events.ScheduleEvent(EVENT_LIGHTNING_BOLT, 15000); + _events.Repeat(randtime(Seconds(8), Seconds(15))); break; default: break; @@ -1060,8 +1029,8 @@ public: } private: - InstanceScript* instance; - EventMap events; + InstanceScript* _instance; + EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override @@ -1070,10 +1039,6 @@ public: } }; -// ######################################################## -// Ashtongue Spiritbinder -// ######################################################## - class npc_ashtongue_spiritbinder : public CreatureScript { public: @@ -1084,44 +1049,72 @@ public: npc_ashtongue_spiritbinderAI(Creature* creature) : ScriptedAI(creature) { Initialize(); - instance = creature->GetInstanceScript(); + _instance = creature->GetInstanceScript(); } void Initialize() { - spiritMend = false; - chainHeal = false; + _spiritMend = false; + _chainHeal = false; } void Reset() override { Initialize(); - if (Unit* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AKAMA_SHADE))) - AttackStart(target); + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + AttackStart(akama); } void JustDied(Unit* /*killer*/) override { - me->DespawnOrUnsummon(5000); + me->DespawnOrUnsummon(Seconds(5)); } void EnterCombat(Unit* /*who*/) override { - events.ScheduleEvent(EVENT_SPIRIT_HEAL, urand (5000, 6000)); + _events.ScheduleEvent(EVENT_SPIRIT_HEAL, randtime(Seconds(5), Seconds(6))); } + void DamageTaken(Unit* /*who*/, uint32& /*damage*/) override + { + if (!_spiritMend) + if (HealthBelowPct(30)) + { + DoCastSelf(SPELL_SPIRIT_MEND); + _spiritMend = true; + _events.ScheduleEvent(EVENT_SPIRIT_MEND_RESET, randtime(Seconds(10),Seconds(15))); + } + + if (!_chainHeal) + if (HealthBelowPct(50)) + { + DoCastSelf(SPELL_CHAIN_HEAL); + _chainHeal = true; + _events.ScheduleEvent(EVENT_CHAIN_HEAL_RESET, randtime(Seconds(10), Seconds(15))); + } + + } + + void EnterEvadeMode(EvadeReason /*why*/) override { } + void UpdateAI(uint32 diff) override { - events.Update(diff); + _events.Update(diff); - while (uint32 eventId = events.ExecuteEvent()) + while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_SPIRIT_HEAL: - DoCast(me, SPELL_SPIRITBINDER_SPIRIT_HEAL); - events.ScheduleEvent(EVENT_SPIRIT_HEAL, urand (13000, 16000)); + DoCastSelf(SPELL_SPIRITBINDER_SPIRIT_HEAL); + _events.Repeat(randtime(Seconds(13), Seconds(16))); + break; + case EVENT_SPIRIT_MEND_RESET: + _spiritMend = false; + break; + case EVENT_CHAIN_HEAL_RESET: + _chainHeal = false; break; default: break; @@ -1131,32 +1124,14 @@ public: if (!UpdateVictim()) return; - if (!spiritMend) - { - if (HealthBelowPct(25)) - { - DoCast(me, SPELL_SPIRIT_MEND); - spiritMend = true; - } - } - - if (!chainHeal) - { - if (HealthBelowPct(40)) - { - DoCast(me, SPELL_CHAIN_HEAL); - chainHeal = true; - } - } - DoMeleeAttackIfReady(); } private: - InstanceScript* instance; - EventMap events; - bool spiritMend; - bool chainHeal; + InstanceScript* _instance; + EventMap _events; + bool _spiritMend; + bool _chainHeal; }; CreatureAI* GetAI(Creature* creature) const override @@ -1165,6 +1140,119 @@ public: } }; +class npc_ashtongue_broken : public CreatureScript +{ +public: + npc_ashtongue_broken() : CreatureScript("npc_ashtongue_broken") { } + + struct npc_ashtongue_brokenAI : public ScriptedAI + { + npc_ashtongue_brokenAI(Creature* creature) : ScriptedAI(creature) + { + _instance = me->GetInstanceScript(); + } + + void MovementInform(uint32 motionType, uint32 /*pointId*/) override + { + if (motionType != POINT_MOTION_TYPE) + return; + + if (Creature* akama = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AKAMA_SHADE))) + me->SetFacingToObject(akama); + } + + void DoAction(int32 actionId) override + { + switch (actionId) + { + case ACTION_BROKEN_SPECIAL: + Talk(SAY_BROKEN_SPECIAL); + break; + case ACTION_BROKEN_HAIL: + me->setFaction(FACTION_FRIENDLY); + Talk(SAY_BROKEN_HAIL); + break; + case ACTION_BROKEN_EMOTE: + me->SetByteValue(UNIT_FIELD_BYTES_1, UNIT_BYTES_1_OFFSET_STAND_STATE, UNIT_STAND_STATE_KNEEL); + break; + default: + break; + } + } + + private: + InstanceScript* _instance; + }; + + + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<npc_ashtongue_brokenAI>(creature); + } +}; + +class spell_shade_soul_channel_serverside : public SpellScriptLoader +{ +public: + spell_shade_soul_channel_serverside() : SpellScriptLoader("spell_shade_soul_channel_serverside") { } + + class spell_shade_soul_channel_serverside_AuraScript : public AuraScript + { + PrepareAuraScript(spell_shade_soul_channel_serverside_AuraScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SHADE_SOUL_CHANNEL_2)) + return false; + return true; + } + + void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + GetTarget()->RemoveAuraFromStack(SPELL_SHADE_SOUL_CHANNEL_2); + } + + void Register() override + { + AfterEffectRemove += AuraEffectRemoveFn(spell_shade_soul_channel_serverside_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_shade_soul_channel_serverside_AuraScript(); + } +}; + +class spell_shade_soul_channel : public SpellScriptLoader +{ +public: + spell_shade_soul_channel() : SpellScriptLoader("spell_shade_soul_channel") { } + + class spell_shade_soul_channel_AuraScript : public AuraScript + { + PrepareAuraScript(spell_shade_soul_channel_AuraScript); + + void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) + { + int32 const maxSlowEff = -99; + if (aurEff->GetAmount() < maxSlowEff) + if (AuraEffect* slowEff = GetEffect(EFFECT_0)) + slowEff->ChangeAmount(maxSlowEff); + } + + void Register() override + { + AfterEffectApply += AuraEffectApplyFn(spell_shade_soul_channel_AuraScript::OnApply, EFFECT_0, SPELL_AURA_MOD_DECREASE_SPEED, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_shade_soul_channel_AuraScript(); + } +}; + void AddSC_boss_shade_of_akama() { new boss_shade_of_akama(); @@ -1176,4 +1264,7 @@ void AddSC_boss_shade_of_akama() new npc_ashtongue_rogue(); new npc_ashtongue_elementalist(); new npc_ashtongue_spiritbinder(); + new npc_ashtongue_broken(); + new spell_shade_soul_channel_serverside(); + new spell_shade_soul_channel(); } diff --git a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp index ae4d17bdad4..0999f1fcd6b 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp @@ -117,7 +117,7 @@ public: DummyEntryCheckPredicate pred; summons.DoAction(EVENT_VOLCANO, pred); events.ScheduleEvent(EVENT_HATEFUL_STRIKE, 5000, GCD_CAST, PHASE_STRIKE); - me->SetSpeed(MOVE_RUN, 1.2f); + me->SetSpeedRate(MOVE_RUN, 1.2f); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, false); } @@ -126,7 +126,7 @@ public: phase = PHASE_CHASE; events.ScheduleEvent(EVENT_VOLCANO, 5000, GCD_CAST, PHASE_CHASE); events.ScheduleEvent(EVENT_SWITCH_TARGET, 10000, 0, PHASE_CHASE); - me->SetSpeed(MOVE_RUN, 0.9f); + me->SetSpeedRate(MOVE_RUN, 0.9f); me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true); } diff --git a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp index 72eb99bd7dc..56d333b2dda 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp @@ -91,7 +91,7 @@ public: void Despawn() { - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); me->RemoveCorpse(); } @@ -218,7 +218,7 @@ public: { Creature* Teron = (ObjectAccessor::GetCreature((*me), TeronGUID)); if (!Teron || !Teron->IsAlive() || Teron->IsInEvadeMode()) - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); CheckTeronTimer = 5000; } else CheckTeronTimer -= diff; @@ -236,9 +236,9 @@ public: return GetInstanceAI<boss_teron_gorefiendAI>(creature); } - struct boss_teron_gorefiendAI : public ScriptedAI + struct boss_teron_gorefiendAI : public BossAI { - boss_teron_gorefiendAI(Creature* creature) : ScriptedAI(creature) + boss_teron_gorefiendAI(Creature* creature) : BossAI(creature, DATA_TERON_GOREFIEND) { Initialize(); instance = creature->GetInstanceScript(); @@ -277,8 +277,7 @@ public: void Reset() override { - instance->SetBossState(DATA_TERON_GOREFIEND, NOT_STARTED); - + _Reset(); Initialize(); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); @@ -316,9 +315,8 @@ public: void JustDied(Unit* /*killer*/) override { - instance->SetBossState(DATA_TERON_GOREFIEND, DONE); - Talk(SAY_DEATH); + _JustDied(); } float CalculateRandomLocation(float Loc, uint32 radius) @@ -363,7 +361,7 @@ public: /** WHAT IS FULLY NECESSARY FOR GOREFIEND TO BE 100% COMPLETE *****/ /************************************************************************/ - Unit* ghost = NULL; + Unit* ghost = nullptr; if (GhostGUID) ghost = ObjectAccessor::GetUnit(*me, GhostGUID); if (ghost && ghost->IsAlive() && ghost->HasAura(SPELL_SHADOW_OF_DEATH)) @@ -379,7 +377,7 @@ public: }*/ for (uint8 i = 0; i < 4; ++i) { - Creature* Construct = NULL; + Creature* Construct = nullptr; float X = CalculateRandomLocation(ghost->GetPositionX(), 10); float Y = CalculateRandomLocation(ghost->GetPositionY(), 10); Construct = me->SummonCreature(CREATURE_SHADOWY_CONSTRUCT, X, Y, ghost->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 45000); @@ -435,17 +433,13 @@ public: for (uint8 i = 0; i < 2; ++i) { - Creature* Shadow = NULL; float X = CalculateRandomLocation(me->GetPositionX(), 10); - Shadow = me->SummonCreature(CREATURE_SHADOWY_CONSTRUCT, X, me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 0); - if (Shadow) + if (Creature* shadow = me->SummonCreature(CREATURE_SHADOWY_CONSTRUCT, X, me->GetPositionY(), me->GetPositionZ(), 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 0)) { - Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1); - if (!target) - target = me->GetVictim(); - - if (target) - Shadow->AI()->AttackStart(target); + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1)) + shadow->AI()->AttackStart(target); + else if (Unit* victim = me->GetVictim()) + shadow->AI()->AttackStart(victim); } } SummonShadowsTimer = 60000; diff --git a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp index 9b33ea88ca7..b9627856ae6 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp @@ -150,7 +150,7 @@ public: DoCast(target, SPELL_IMPALING_SPINE, true); SpineTargetGUID = target->GetGUID(); //must let target summon, otherwise you cannot click the spine - target->SummonGameObject(GO_NAJENTUS_SPINE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), me->GetOrientation(), 0, 0, 0, 0, 30); + target->SummonGameObject(GO_NAJENTUS_SPINE, *target, G3D::Quat(), 30); Talk(SAY_NEEDLE); events.DelayEvents(1500, GCD_CAST); events.DelayEvents(15000, GCD_YELL); diff --git a/src/server/scripts/Outland/BlackTemple/illidari_council.cpp b/src/server/scripts/Outland/BlackTemple/illidari_council.cpp index d883a48b630..06b492e32d7 100644 --- a/src/server/scripts/Outland/BlackTemple/illidari_council.cpp +++ b/src/server/scripts/Outland/BlackTemple/illidari_council.cpp @@ -90,8 +90,6 @@ enum IllidariCouncil SPELL_BERSERK = 45078 }; -#define ERROR_INST_DATA "SD2 ERROR: Instance Data for Black Temple not set properly; Illidari Council event will not function properly." - struct CouncilYells { int32 entry; @@ -165,7 +163,7 @@ public: Council[1] = instance->GetGuidData(DATA_VERAS_DARKSHADOW); Council[2] = instance->GetGuidData(DATA_LADY_MALANDE); Council[3] = instance->GetGuidData(DATA_HIGH_NETHERMANCER_ZEREVOR); - } else TC_LOG_ERROR("scripts", ERROR_INST_DATA); + } } void EnterCombat(Unit* /*who*/) override { } @@ -231,6 +229,7 @@ public: { Initialize(); instance = creature->GetInstanceScript(); + SetBoundary(instance->GetBossBoundary(DATA_ILLIDARI_COUNCIL)); } void Initialize() @@ -257,7 +256,7 @@ public: { Initialize(); - Creature* pMember = NULL; + Creature* pMember = nullptr; for (uint8 i = 0; i < 4; ++i) { pMember = ObjectAccessor::GetCreature((*me), Council[i]); @@ -330,16 +329,16 @@ public: if (DeathCount > 3) { if (Creature* VoiceTrigger = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_BLOOD_ELF_COUNCIL_VOICE))) - VoiceTrigger->DealDamage(VoiceTrigger, VoiceTrigger->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + VoiceTrigger->DealDamage(VoiceTrigger, VoiceTrigger->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); instance->SetBossState(DATA_ILLIDARI_COUNCIL, DONE); //me->SummonCreature(AKAMAID, 746.466980f, 304.394989f, 311.90208f, 6.272870f, TEMPSUMMON_DEAD_DESPAWN, 0); - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); return; } Creature* pMember = (ObjectAccessor::GetCreature(*me, Council[DeathCount])); if (pMember && pMember->IsAlive()) - pMember->DealDamage(pMember, pMember->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + pMember->DealDamage(pMember, pMember->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); ++DeathCount; EndEventTimer = 1500; } else EndEventTimer -= diff; @@ -922,7 +921,7 @@ public: if (dmgInfo.GetAttacker() == target) return; int32 bp = absorbAmount / 2; - target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_REFLECTIVE_SHIELD_T, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_REFLECTIVE_SHIELD_T, &bp, nullptr, nullptr, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp index 86ad7958957..bac996918ac 100644 --- a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp @@ -35,6 +35,20 @@ DoorData const doorData[] = { 0, 0, DOOR_TYPE_ROOM } // END }; +BossBoundaryData const boundaries = +{ + { DATA_HIGH_WARLORD_NAJENTUS, new RectangleBoundary(394.0f, 479.4f, 707.8f, 859.1f) }, + { DATA_SUPREMUS, new RectangleBoundary(556.1f, 850.2f, 542.0f, 1001.0f) }, + { DATA_SHADE_OF_AKAMA, new RectangleBoundary(406.8f, 564.0f, 327.9f, 473.5f) }, + { DATA_TERON_GOREFIEND, new RectangleBoundary(512.5f, 613.3f, 373.2f, 432.0f) }, + { DATA_TERON_GOREFIEND, new ZRangeBoundary(179.5f, 223.6f) }, + { DATA_GURTOGG_BLOODBOIL, new RectangleBoundary(720.5f, 864.5f, 159.3f, 316.0f) }, + { DATA_RELIQUARY_OF_SOULS, new RectangleBoundary(435.9f, 558.8f, 113.3f, 229.6f) }, + { DATA_MOTHER_SHAHRAZ, new RectangleBoundary(903.4f, 982.1f, 92.4f, 476.7f) }, + { DATA_ILLIDARI_COUNCIL, new EllipseBoundary(Position(696.6f, 305.0f), 70.0 , 85.0) }, + { DATA_ILLIDAN_STORMRAGE, new EllipseBoundary(Position(694.8f, 309.0f), 70.0 , 85.0) } +}; + class instance_black_temple : public InstanceMapScript { public: @@ -47,6 +61,7 @@ class instance_black_temple : public InstanceMapScript SetHeaders(DataHeader); SetBossNumber(EncounterCount); LoadDoorData(doorData); + LoadBossBoundaries(boundaries); } void OnCreatureCreate(Creature* creature) override diff --git a/src/server/scripts/Outland/CMakeLists.txt b/src/server/scripts/Outland/CMakeLists.txt deleted file mode 100644 index 55b0452fb0b..00000000000 --- a/src/server/scripts/Outland/CMakeLists.txt +++ /dev/null @@ -1,128 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - Outland/zone_nagrand.cpp - Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h - Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp - Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp - Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp - Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp - Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp - Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp - Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h - Outland/HellfireCitadel/BloodFurnace/boss_the_maker.cpp - Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp - Outland/HellfireCitadel/BloodFurnace/blood_furnace.h - Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp - Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp - Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h - Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp - Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp - Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp - Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp - Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp - Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp - Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp - Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp - Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp - Outland/CoilfangReservoir/SteamVault/steam_vault.h - Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp - Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp - Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp - Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h - Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp - Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp - Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp - Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp - Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp - Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h - Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp - Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp - Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp - Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp - Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp - Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp - Outland/zone_shattrath_city.cpp - Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp - Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp - Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp - Outland/TempestKeep/Mechanar/mechanar.h - Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp - Outland/TempestKeep/Mechanar/instance_mechanar.cpp - Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp - Outland/TempestKeep/Eye/the_eye.h - Outland/TempestKeep/Eye/instance_the_eye.cpp - Outland/TempestKeep/Eye/boss_void_reaver.cpp - Outland/TempestKeep/Eye/boss_astromancer.cpp - Outland/TempestKeep/Eye/boss_alar.cpp - Outland/TempestKeep/Eye/boss_kaelthas.cpp - Outland/TempestKeep/Eye/the_eye.cpp - Outland/TempestKeep/botanica/the_botanica.h - Outland/TempestKeep/botanica/instance_the_botanica.cpp - Outland/TempestKeep/botanica/boss_commander_sarannis.cpp - Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp - Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp - Outland/TempestKeep/botanica/boss_warp_splinter.cpp - Outland/TempestKeep/botanica/boss_laj.cpp - Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp - Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp - Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp - Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp - Outland/TempestKeep/arcatraz/instance_arcatraz.cpp - Outland/TempestKeep/arcatraz/arcatraz.h - Outland/TempestKeep/arcatraz/arcatraz.cpp - Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp - Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp - Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp - Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h - Outland/Auchindoun/ManaTombs/boss_pandemonius.cpp - Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp - Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp - Outland/Auchindoun/ManaTombs/mana_tombs.h - Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp - Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp - Outland/Auchindoun/SethekkHalls/boss_anzu.cpp - Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp - Outland/Auchindoun/SethekkHalls/sethekk_halls.h - Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp - Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp - Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp - Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp - Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp - Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h - Outland/boss_doomwalker.cpp - Outland/zone_terokkar_forest.cpp - Outland/zone_hellfire_peninsula.cpp - Outland/boss_doomlord_kazzak.cpp - Outland/BlackTemple/boss_teron_gorefiend.cpp - Outland/BlackTemple/black_temple.h - Outland/BlackTemple/illidari_council.cpp - Outland/BlackTemple/boss_shade_of_akama.cpp - Outland/BlackTemple/boss_supremus.cpp - Outland/BlackTemple/black_temple.cpp - Outland/BlackTemple/boss_mother_shahraz.cpp - Outland/BlackTemple/instance_black_temple.cpp - Outland/BlackTemple/boss_reliquary_of_souls.cpp - Outland/BlackTemple/boss_warlord_najentus.cpp - Outland/BlackTemple/boss_gurtogg_bloodboil.cpp - Outland/BlackTemple/boss_illidan.cpp - Outland/zone_shadowmoon_valley.cpp - Outland/zone_blades_edge_mountains.cpp - Outland/GruulsLair/boss_high_king_maulgar.cpp - Outland/GruulsLair/boss_gruul.cpp - Outland/GruulsLair/gruuls_lair.h - Outland/GruulsLair/instance_gruuls_lair.cpp - Outland/zone_netherstorm.cpp - Outland/zone_zangarmarsh.cpp -) - -message(" -> Prepared: Outland") diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp index e24499c3aee..3ddf0fec416 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp @@ -585,8 +585,8 @@ public: void Reset() override { - me->SetSpeed(MOVE_WALK, 0.6f); // walk - me->SetSpeed(MOVE_RUN, 0.6f); // run + me->SetSpeedRate(MOVE_WALK, 0.6f); // walk + me->SetSpeedRate(MOVE_RUN, 0.6f); // run Initialize(); //search for nearest waypoint (up on stairs) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp index 8d117f7c3ef..f72b9a8d2ca 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp @@ -244,7 +244,7 @@ public: CheckChannelers(); Initialize(); me->SetCanDualWield(true); - me->SetSpeed(MOVE_RUN, 2.0f, true); + me->SetSpeedRate(MOVE_RUN, 2.0f); me->SetDisplayId(MODEL_NIGHTELF); me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID , 0); me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID+1, 0); diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp new file mode 100644 index 00000000000..62552a3bf61 --- /dev/null +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp @@ -0,0 +1,1046 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "CreatureTextMgr.h" +#include "LFGMgr.h" +#include "ScriptedGossip.h" +#include "ScriptedCreature.h" +#include "ScriptMgr.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "the_slave_pens.h" + +enum Spells +{ + // Ahune + SPELL_SYNCH_HEALTH = 46430, + SPELL_AHUNES_SHIELD = 45954, + SPELL_STAY_SUBMERGED = 46981, + SPELL_AHUNE_SELF_STUN = 46416, + SPELL_AHUNE_ACHIEVEMENT = 62043, + SPELL_AHUNE_SPANKY_HANDS = 46146, + SPELL_COLD_SLAP = 46145, + SPELL_RESURFACE = 46402, + SPELL_SUBMERGED = 37751, + SPELL_STAND = 37752, + + //Earther Ring Flamecaller + SPELL_FIND_OPENING_VISUAL = 45964, + SPELL_FIND_OPENING_BEAM_END = 46333, + SPELL_FIND_OPENING_TRIGGER = 46341, + SPELL_FIND_OPENING_CHANNEL = 46345, + SPELL_BONFIRE_VISUAL = 46339, + SPELL_FOUND_OPENING = 46421, + + //Ahune Bunny + SPELL_SUMMON_COLDWEAVE = 46143, + SPELL_SUMMON_FROSTWIND = 46382, + SPELL_SUMMON_HAILSTONE = 46176, + SPELL_SUMMONING_VISUAL_1 = 45937, + SPELL_SUMMONING_RHYME_AURA = 45926, + SPELL_SUMMONING_RHYME_BONFIRE = 45930, + SPELL_FORCE_WHISP_FLIGHT = 46603, + SPELL_SHAMANS_LOOK_FOR_OPENING = 46422, + SPELL_CLOSE_OPENING_VISUAL = 46236, + SPELL_ICE_BOMBARD = 46397, + SPELL_ICE_BOMBARDMENT_DEST_PICKER = 46398, + SPELL_ICE_BOMBARDMENT = 46396, + + // Ice Spear + SPELL_SUMMON_ICE_SPEAR_BUNNY = 46359, + SPELL_ICE_SPEAR_KNOCKBACK = 46360, + SPELL_SUMMON_ICE_SPEAR_GO = 46369, + SPELL_ICE_SPEAR_AURA = 46371, + SPELL_ICE_SPEAR_TARGET_PICKER = 46372, + SPELL_ICE_SPEAR_DELAY = 46878, + SPELL_ICE_SPEAR_VISUAL = 75498, + + // Slippery Floor + SPELL_SLIPPERY_FLOOR_AMBIENT = 46314, + SPELL_SLIPPERY_FLOOR_PERIODIC = 46320, + SPELL_SLIPPERY_FLOOR_SLIP = 45947, + SPELL_SLIPPERY_FLOOR_YOU_SLIPPED = 45946, + + // Frozen Core + SPELL_SUICIDE = 45254, + SPELL_SUMMON_LOOT_MISSILE = 45941, + SPELL_FROZEN_CORE_GETS_HIT = 46810, + SPELL_MINION_DESPAWNER = 46843, + SPELL_GHOST_DISGUISE = 46786 +}; + +enum Emotes +{ + EMOTE_EARTHEN_ASSAULT = 0, + EMOTE_RETREAT = 0, + EMOTE_RESURFACE = 1 +}; + +enum Says +{ + SAY_PLAYER_TEXT_1 = 0, + SAY_PLAYER_TEXT_2 = 1, + SAY_PLAYER_TEXT_3 = 2 +}; + +enum Events +{ + EVENT_EMERGE = 1, + EVENT_INITIAL_EMERGE = 2, + EVENT_SYNCH_HEALTH = 3, + EVENT_LOOKFOROPENING_0 = 4, + EVENT_LOOKFOROPENING_1 = 5, + EVENT_LOOKFOROPENING_2 = 6, + EVENT_SUMMON_HAILSTONE = 7, + EVENT_SUMMON_COLDWEAVE = 8, + EVENT_SUMMON_FROSTWIND = 9, + EVENT_SUMMON_AHUNE = 10, + EVENT_CLOSE_OPENING = 11, + EVENT_AHUNE_PHASE_ONE = 12, + EVENT_AHUNE_PHASE_TWO = 13, + EVENT_START_LOOKING_FOR_OPENING = 14, + EVENT_STOP_LOOKING_FOR_OPENING = 15 +}; + +enum Actions +{ + ACTION_START_EVENT = -2574500, + ACTION_AHUNE_RETREAT = -2586500, + ACTION_AHUNE_RESURFACE = -2586501, + ACTION_EMOTE_RESURFACE = -2575400 +}; + +enum Phases +{ + PHASE_ONE = 0, + PHASE_TWO = 1 +}; + +enum Points +{ + POINT_FLAMECALLER_000, + POINT_FLAMECALLER_001, + POINT_FLAMECALLER_002 +}; + +enum Misc +{ + MAX_FLAMECALLERS = 3 +}; + +Position const SummonPositions[] = +{ + { -99.1021f, -233.7526f, -1.22307f, 1.588250f }, // Ahune + { -98.0151f, -230.4555f, -1.21089f, 1.797689f }, // Frozen Core + { -143.172f, -147.6801f, -3.16113f, 4.852015f }, // Bonfire Bunny 000 + { -134.304f, -145.7803f, -1.70332f, 4.677482f }, // Bonfire Bunny 001 + { -125.036f, -144.2065f, -1.91660f, 4.991642f }, // Bonfire Bunny 002 + { -69.8121f, -162.4954f, -2.30451f, 1.710423f }, // Wisp Source Bunny + { -98.1029f, -230.7864f, -10.8085f, 1.448623f } // Wisp Dest Bunny +}; + +Position const FlameCallerSpots[] = +{ + { -145.2233f, -137.5543f, -1.59056f, 5.427049f }, + { -137.4383f, -136.4050f, -1.72384f, 5.336747f }, + { -129.0413f, -132.1494f, -2.09285f, 5.460842f } +}; + +class boss_ahune : public CreatureScript +{ +public: + boss_ahune() : CreatureScript("boss_ahune") { } + + struct boss_ahuneAI : public BossAI + { + boss_ahuneAI(Creature* creature) : BossAI(creature, DATA_AHUNE) + { + me->SetControlled(true, UNIT_STATE_ROOT); + } + + void EnterCombat(Unit* /*who*/) override + { + _EnterCombat(); + events.ScheduleEvent(EVENT_INITIAL_EMERGE, Milliseconds(4)); + events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3)); + } + + void EnterEvadeMode(EvadeReason /*why*/) override + { + if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AHUNE_BUNNY))) + ahuneBunny->AI()->EnterEvadeMode(); + summons.DespawnAll(); + me->DespawnOrUnsummon(); + } + + void JustDied(Unit* /*killer*/) override + { + instance->DoCastSpellOnPlayers(SPELL_AHUNE_ACHIEVEMENT); + + if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AHUNE_BUNNY))) + me->Kill(ahuneBunny); + if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE))) + me->Kill(frozenCore); + + Map::PlayerList const& players = me->GetMap()->GetPlayers(); + if (!players.isEmpty()) + { + if (Group* group = players.begin()->GetSource()->GetGroup()) + if (group->isLFGGroup()) + sLFGMgr->FinishDungeon(group->GetGUID(), 286); + } + + _JustDied(); + } + + void DoAction(int32 action) override + { + if (action == ACTION_AHUNE_RETREAT) + { + Submerge(); + events.ScheduleEvent(EVENT_EMERGE, Seconds(35)); + } + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + events.Update(diff); + + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_INITIAL_EMERGE: + DoCast(me, SPELL_STAND); + DoCast(me, SPELL_AHUNE_SPANKY_HANDS); + DoCast(me, SPELL_AHUNES_SHIELD); + break; + case EVENT_EMERGE: + Emerge(); + break; + case EVENT_SYNCH_HEALTH: + if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE))) + DoCast(frozenCore, SPELL_SYNCH_HEALTH, true); + else + DoCast(me, SPELL_SUICIDE); + events.Repeat(Seconds(3)); + break; + default: + break; + } + } + DoMeleeAttackIfReady(); + } + + void Emerge() + { + if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE))) + frozenCore->AI()->DoAction(ACTION_AHUNE_RESURFACE); + + DoCast(me, SPELL_AHUNES_SHIELD); + me->RemoveAurasDueToSpell(SPELL_AHUNE_SELF_STUN); + me->RemoveAurasDueToSpell(SPELL_STAY_SUBMERGED); + DoCast(me, SPELL_STAND); + DoCast(me, SPELL_RESURFACE, true); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3)); + } + + void Submerge() + { + if (Creature* frozenCore = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FROZEN_CORE))) + frozenCore->AI()->DoAction(ACTION_AHUNE_RETREAT); + me->RemoveAurasDueToSpell(SPELL_AHUNES_SHIELD); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_31); + DoCast(me, SPELL_SUBMERGED, true); + DoCast(me, SPELL_AHUNE_SELF_STUN, true); + DoCast(me, SPELL_STAY_SUBMERGED, true); + me->HandleEmoteCommand(EMOTE_ONESHOT_SUBMERGE); + events.Reset(); + } + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<boss_ahuneAI>(creature); + } +}; + +class npc_frozen_core : public CreatureScript +{ +public: + npc_frozen_core() : CreatureScript("npc_frozen_core") { } + + struct npc_frozen_coreAI : public ScriptedAI + { + npc_frozen_coreAI(Creature* creature) : ScriptedAI(creature) + { + _instance = me->GetInstanceScript(); + Initialize(); + } + + void Initialize() + { + me->SetReactState(REACT_PASSIVE); + me->setRegeneratingHealth(false); + DoCast(me, SPELL_FROZEN_CORE_GETS_HIT); + DoCast(me, SPELL_ICE_SPEAR_AURA); + } + + void JustDied(Unit* /*killer*/) override + { + if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE))) + me->Kill(ahune); + + DoCast(SPELL_SUMMON_LOOT_MISSILE); + DoCast(SPELL_MINION_DESPAWNER); + } + + void DoAction(int32 action) override + { + if (action == ACTION_AHUNE_RETREAT) + { + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); + me->RemoveAurasDueToSpell(SPELL_ICE_SPEAR_AURA); + _events.ScheduleEvent(EVENT_SYNCH_HEALTH, Seconds(3), 0, PHASE_TWO); + } + else if (action == ACTION_AHUNE_RESURFACE) + { + _events.Reset(); + DoCast(me, SPELL_ICE_SPEAR_AURA); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_IMMUNE_TO_PC); + } + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_SYNCH_HEALTH: + if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE))) + DoCast(ahune, SPELL_SYNCH_HEALTH, true); + else + DoCast(me, SPELL_SUICIDE); + _events.Repeat(Seconds(3)); + break; + default: + break; + } + } + } + + private: + InstanceScript* _instance; + EventMap _events; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<npc_frozen_coreAI>(creature); + } +}; + +class npc_ahune_bunny : public CreatureScript +{ +public: + npc_ahune_bunny() : CreatureScript("npc_ahune_bunny") { } + + struct npc_ahune_bunnyAI : public ScriptedAI + { + npc_ahune_bunnyAI(Creature* creature) : ScriptedAI(creature), _summons(me) + { + _instance = me->GetInstanceScript(); + _submerged = false; + } + + void JustSummoned(Creature* summon) override + { + if (summon->GetEntry() == NPC_AHUNE) + return; + + summon->SetInCombatWithZone(); + _summons.Summon(summon); + } + + void JustDied(Unit* /*killer*/) override + { + _summons.DespawnAll(); + ResetFlameCallers(); + } + + void EnterEvadeMode(EvadeReason /*why*/) override + { + _EnterEvadeMode(); + _summons.DespawnAll(); + ResetFlameCallers(); + + me->SummonGameObject(GO_ICE_STONE, -69.90455f, -162.2449f, -2.366563f, 2.426008f, G3D::Quat(0.0f, 0.0f, 0.9366722f, 0.3502074f), 0); + } + + void DoAction(int32 action) override + { + if (action == ACTION_START_EVENT) + { + DoCast(me, SPELL_SUMMONING_VISUAL_1); + me->SummonCreature(NPC_WHISP_SOURCE_BUNNY, SummonPositions[5], TEMPSUMMON_MANUAL_DESPAWN); + me->SummonCreature(NPC_WHISP_DEST_BUNNY, SummonPositions[6], TEMPSUMMON_MANUAL_DESPAWN); + me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_000, SummonPositions[2], TEMPSUMMON_MANUAL_DESPAWN); + me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_001, SummonPositions[3], TEMPSUMMON_MANUAL_DESPAWN); + me->SummonCreature(NPC_SHAMAN_BONFIRE_BUNNY_002, SummonPositions[4], TEMPSUMMON_MANUAL_DESPAWN); + + for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter) + if (Creature* flameCaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter))) + flameCaller->GetMotionMaster()->MovePoint(counter, FlameCallerSpots[counter].GetPosition()); + + _submerged = false; + _events.Reset(); + _events.SetPhase(PHASE_ONE); + _events.ScheduleEvent(EVENT_SUMMON_AHUNE, Seconds(10)); + _events.ScheduleEvent(EVENT_START_LOOKING_FOR_OPENING, Seconds(14), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_SUMMON_COLDWEAVE, Seconds(22), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_SUMMON_HAILSTONE, Seconds(14), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_AHUNE_PHASE_TWO, Seconds(108), 0, PHASE_ONE); + } + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + _events.Update(diff); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_START_LOOKING_FOR_OPENING: + Talk(EMOTE_EARTHEN_ASSAULT); + for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter) + if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter))) + DoCast(flamecaller, SPELL_SHAMANS_LOOK_FOR_OPENING, true); + break; + case EVENT_SUMMON_HAILSTONE: + DoCast(SPELL_SUMMON_HAILSTONE); + break; + case EVENT_SUMMON_COLDWEAVE: + DoCast(SPELL_SUMMON_COLDWEAVE); + DoCast(SPELL_SUMMON_COLDWEAVE); + _events.Repeat(Seconds(8)); + if (_submerged) + _events.ScheduleEvent(EVENT_SUMMON_FROSTWIND, Seconds(4), 0, PHASE_ONE); + break; + case EVENT_SUMMON_FROSTWIND: + DoCast(SPELL_SUMMON_FROSTWIND); + break; + case EVENT_SUMMON_AHUNE: + if (TempSummon* ahune = me->SummonCreature(NPC_AHUNE, SummonPositions[0], TEMPSUMMON_DEAD_DESPAWN)) + { + ahune->SummonCreature(NPC_FROZEN_CORE, SummonPositions[1], TEMPSUMMON_CORPSE_DESPAWN); + ahune->SetInCombatWithZone(); + DoCast(ahune, SPELL_RESURFACE); + } + break; + case EVENT_CLOSE_OPENING: + if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000))) + flamecaller->AI()->DoAction(ACTION_EMOTE_RESURFACE); + DoCast(SPELL_CLOSE_OPENING_VISUAL); + DoCast(me, SPELL_ICE_BOMBARD); + break; + case EVENT_AHUNE_PHASE_TWO: + if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000))) + DoCast(flamecaller, SPELL_FOUND_OPENING); + if (Creature* ahune = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_AHUNE))) + ahune->AI()->DoAction(ACTION_AHUNE_RETREAT); + _events.Reset(); + _events.SetPhase(PHASE_TWO); + _events.ScheduleEvent(EVENT_CLOSE_OPENING, Seconds(25), 0, PHASE_TWO); + _events.ScheduleEvent(EVENT_AHUNE_PHASE_ONE, Seconds(35), 0, PHASE_TWO); + break; + case EVENT_AHUNE_PHASE_ONE: + _submerged = true; + _events.Reset(); + _events.SetPhase(PHASE_ONE); + _events.ScheduleEvent(EVENT_SUMMON_COLDWEAVE, Seconds(8), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_SUMMON_HAILSTONE, Seconds(5), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_START_LOOKING_FOR_OPENING, Seconds(5), 0, PHASE_ONE); + _events.ScheduleEvent(EVENT_AHUNE_PHASE_TWO, Seconds(100), 0, PHASE_ONE); + break; + default: + break; + } + } + } + + void ResetFlameCallers() + { + for (uint8 counter = 0; counter < MAX_FLAMECALLERS; ++counter) + if (Creature* flamecaller = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FLAMECALLER_000 + counter))) + flamecaller->AI()->EnterEvadeMode(); + } + + private: + InstanceScript* _instance; + EventMap _events; + SummonList _summons; + bool _submerged; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<npc_ahune_bunnyAI>(creature); + } +}; + +class npc_earthen_ring_flamecaller : public CreatureScript +{ +public: + npc_earthen_ring_flamecaller() : CreatureScript("npc_earthen_ring_flamecaller") { } + + struct npc_earthen_ring_flamecallerAI : public ScriptedAI + { + npc_earthen_ring_flamecallerAI(Creature* creature) : ScriptedAI(creature) + { + _instance = me->GetInstanceScript(); + _mySpot = 0; + } + + void Reset() override + { + _events.Reset(); + } + + void MovementInform(uint32 motionType, uint32 pointId) override + { + if (motionType != POINT_MOTION_TYPE) + return; + + switch (pointId) + { + case POINT_FLAMECALLER_000: + _mySpot = POINT_FLAMECALLER_000; + me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation()); + break; + case POINT_FLAMECALLER_001: + _mySpot = POINT_FLAMECALLER_001; + me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation()); + break; + case POINT_FLAMECALLER_002: + _mySpot = POINT_FLAMECALLER_002; + me->SetOrientation(FlameCallerSpots[_mySpot].GetOrientation()); + break; + default: + break; + } + + DoCast(me, SPELL_FIND_OPENING_CHANNEL); + } + + void SpellHit(Unit* /*caster*/, SpellInfo const* spellInfo) override + { + switch (spellInfo->Id) + { + case SPELL_SHAMANS_LOOK_FOR_OPENING: + _events.ScheduleEvent(EVENT_LOOKFOROPENING_0, Seconds(17)); + break; + case SPELL_FOUND_OPENING: + Talk(EMOTE_RETREAT); + break; + default: + break; + } + } + + void DoAction(int action) override + { + if (action == ACTION_EMOTE_RESURFACE) + Talk(EMOTE_RESURFACE); + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_LOOKFOROPENING_0: + LookOpening(true, 0); + _events.ScheduleEvent(EVENT_LOOKFOROPENING_1, Seconds(26)); + break; + case EVENT_LOOKFOROPENING_1: + LookOpening(true, 1); + _events.ScheduleEvent(EVENT_LOOKFOROPENING_2, Seconds(25)); + break; + case EVENT_LOOKFOROPENING_2: + LookOpening(true, 2); + _events.ScheduleEvent(EVENT_STOP_LOOKING_FOR_OPENING, Seconds(27)); + break; + case EVENT_STOP_LOOKING_FOR_OPENING: + LookOpening(false, _mySpot); + break; + default: + break; + } + } + } + + void LookOpening(bool activate, uint8 spot) + { + if (_mySpot != spot) + return; + + if (Creature* bonfireBunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BONFIRE_BUNNY_000 + spot))) + if (Creature* beamBunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BEAM_BUNNY_000 + spot))) + { + if (activate) + { + DoCast(bonfireBunny, SPELL_FIND_OPENING_TRIGGER); + bonfireBunny->CastSpell(beamBunny, SPELL_FIND_OPENING_VISUAL, true); + } + else + { + DoCast(me, SPELL_FIND_OPENING_CHANNEL); + bonfireBunny->CastStop(); + beamBunny->RemoveAurasDueToSpell(SPELL_FIND_OPENING_BEAM_END); + } + } + } + + private: + EventMap _events; + InstanceScript* _instance; + uint8 _mySpot; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetInstanceAI<npc_earthen_ring_flamecallerAI>(creature); + } +}; + +class go_ahune_ice_stone : public GameObjectScript +{ +public: + go_ahune_ice_stone() : GameObjectScript("go_ahune_ice_stone") { } + + bool OnGossipSelect(Player* player, GameObject* go, uint32 /*sender*/, uint32 /*action*/) + { + InstanceScript* instance = go->GetInstanceScript(); + if (!instance) + return false; + + player->PlayerTalkClass->ClearMenus(); + + if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*go, instance->GetGuidData(DATA_AHUNE_BUNNY))) + { + ahuneBunny->AI()->DoAction(ACTION_START_EVENT); + ahuneBunny->SetInCombatWithZone(); + } + if (Creature* luma = ObjectAccessor::GetCreature(*go, instance->GetGuidData(DATA_LUMA_SKYMOTHER))) + luma->CastSpell(player, SPELL_SUMMONING_RHYME_AURA, true); + player->CLOSE_GOSSIP_MENU(); + go->Delete(); + + return true; + } +}; + +// 46430 - Synch Health +class spell_ahune_synch_health : public SpellScriptLoader +{ +public: + spell_ahune_synch_health() : SpellScriptLoader("spell_ahune_synch_health") { } + + class spell_ahune_synch_health_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ahune_synch_health_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SYNCH_HEALTH)) + return false; + return true; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + if (Unit* target = GetHitUnit()) + if (Unit* caster = GetCaster()) + target->SetHealth(caster->GetHealth()); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_ahune_synch_health_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_ahune_synch_health_SpellScript(); + } +}; + +// 45926 - Summoning Rhyme Aura +class spell_summoning_rhyme_aura : public SpellScriptLoader +{ +public: + spell_summoning_rhyme_aura() : SpellScriptLoader("spell_summoning_rhyme_aura") { } + + class spell_summoning_rhyme_aura_AuraScript : public AuraScript + { + PrepareAuraScript(spell_summoning_rhyme_aura_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_WHISP_FLIGHT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMONING_RHYME_BONFIRE)) + return false; + return true; + } + + void PeriodicTick(AuraEffect const* aurEff) + { + Creature* caster = GetCaster()->ToCreature(); + Player* player = GetTarget()->ToPlayer(); + + if (!caster || !player) + return; + + player->CastSpell(player, SPELL_FORCE_WHISP_FLIGHT); + + switch (aurEff->GetTickNumber()) + { + case 1: + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_1, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + player->CastSpell(player, SPELL_SUMMONING_RHYME_BONFIRE, true); + break; + case 2: + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_2, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + break; + case 3: + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_3, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + Remove(); + break; + } + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_summoning_rhyme_aura_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_summoning_rhyme_aura_AuraScript(); + } +}; + +// 46878 - Summon Ice Spear Delayer +class spell_summon_ice_spear_delayer : public SpellScriptLoader +{ +public: + spell_summon_ice_spear_delayer() : SpellScriptLoader("spell_summon_ice_spear_delayer") { } + + class spell_summon_ice_spear_delayer_AuraScript : public AuraScript + { + PrepareAuraScript(spell_summon_ice_spear_delayer_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_GO) || !sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_KNOCKBACK)) + return false; + return true; + } + + void PeriodicTick(AuraEffect const* aurEff) + { + if (Unit* tmpCaster = GetCaster()) + if (Creature* caster = tmpCaster->ToCreature()) + switch (aurEff->GetTickNumber()) + { + case 1: + caster->CastSpell(caster, SPELL_SUMMON_ICE_SPEAR_GO); + break; + case 3: + if (GameObject* spike = caster->FindNearestGameObject(GO_ICE_SPEAR, 3.0f)) + spike->UseDoorOrButton(); + caster->AI()->DoCastAOE(SPELL_ICE_SPEAR_KNOCKBACK, true); + break; + case 5: + if (GameObject* spike = caster->FindNearestGameObject(GO_ICE_SPEAR, 3.0f)) + spike->Delete(); + caster->DespawnOrUnsummon(); + break; + default: + break; + } + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_summon_ice_spear_delayer_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_summon_ice_spear_delayer_AuraScript(); + } +}; + +// 46371 - Ice Spear Control Aura +class spell_ice_spear_control_aura : public SpellScriptLoader +{ +public: + spell_ice_spear_control_aura() : SpellScriptLoader("spell_ice_spear_control_aura") { } + + class spell_ice_spear_control_aura_AuraScript : public AuraScript + { + PrepareAuraScript(spell_ice_spear_control_aura_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_TARGET_PICKER)) + return false; + return true; + } + + void PeriodicTick(AuraEffect const* /*aurEff*/) + { + if (Unit* caster = GetCaster()) + caster->CastSpell(caster, SPELL_ICE_SPEAR_TARGET_PICKER); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_ice_spear_control_aura_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_ice_spear_control_aura_AuraScript(); + } +}; + +// 46372 - Ice Spear Target Picker +class spell_ice_spear_target_picker : public SpellScriptLoader +{ +public: + spell_ice_spear_target_picker() : SpellScriptLoader("spell_ice_spear_target_picker") { } + + class spell_ice_spear_target_picker_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ice_spear_target_picker_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_BUNNY)) + return false; + return true; + } + + void FilterTargets(std::list<WorldObject*>& targets) + { + if (targets.empty()) + return; + + WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets); + targets.clear(); + targets.push_back(target); + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ICE_SPEAR_BUNNY, true); + } + + void Register() override + { + OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ice_spear_target_picker_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); + OnEffectHitTarget += SpellEffectFn(spell_ice_spear_target_picker_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_ice_spear_target_picker_SpellScript(); + } +}; + +// 46320 - Spell Slippery Floor Periodic +class spell_slippery_floor_periodic : public SpellScriptLoader +{ +public: + spell_slippery_floor_periodic() : SpellScriptLoader("spell_slippery_floor_periodic") { } + + class spell_slippery_floor_periodic_SpellScript : public SpellScript + { + PrepareSpellScript(spell_slippery_floor_periodic_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SLIPPERY_FLOOR_SLIP)) + return false; + return true; + } + + void HandleScriptEffect(SpellEffIndex /*effIndex*/) + { + if (Unit* target = GetHitUnit()) + if (target->isMoving()) + { + target->CastSpell(target, SPELL_SLIPPERY_FLOOR_SLIP, true); + target->CastSpell(target, SPELL_SLIPPERY_FLOOR_YOU_SLIPPED, true); + } + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_slippery_floor_periodic_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_slippery_floor_periodic_SpellScript(); + } +}; + +// 46146 - Ahune Spanky Hands +class spell_ahune_spanky_hands : public SpellScriptLoader +{ +public: + spell_ahune_spanky_hands() : SpellScriptLoader("spell_ahune_spanky_hands") { } + + class spell_ahune_spanky_hands_AuraScript : public AuraScript + { + PrepareAuraScript(spell_ahune_spanky_hands_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_COLD_SLAP)) + return false; + return true; + } + + void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_COLD_SLAP, true); + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_ahune_spanky_hands_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_ahune_spanky_hands_AuraScript(); + } +}; + +class spell_ahune_minion_despawner : public SpellScriptLoader +{ +public: + spell_ahune_minion_despawner() : SpellScriptLoader("spell_ahune_minion_despawner") { } + + class spell_ahune_minion_despawner_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ahune_minion_despawner_SpellScript); + + void HandleScript(SpellEffIndex /*effIndex*/) + { + if (GetHitCreature()) + GetHitCreature()->DespawnOrUnsummon(); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_ahune_minion_despawner_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_APPLY_AURA); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_ahune_minion_despawner_SpellScript(); + } +}; + +// 46398 - Spell Ice Bombardment Dest Picker +class spell_ice_bombardment_dest_picker : public SpellScriptLoader +{ +public: + spell_ice_bombardment_dest_picker() : SpellScriptLoader("spell_ice_bombardment_dest_picker") { } + + class spell_ice_bombardment_dest_picker_SpellScript : public SpellScript + { + PrepareSpellScript(spell_ice_bombardment_dest_picker_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BOMBARDMENT)) + return false; + return true; + } + + void HandleScriptEffect(SpellEffIndex /*effIndex*/) + { + GetCaster()->CastSpell(GetHitDest()->GetPositionX(), GetHitDest()->GetPositionY(), GetHitDest()->GetPositionZ(), SPELL_ICE_BOMBARDMENT, true); + } + + void Register() override + { + OnEffectHit += SpellEffectFn(spell_ice_bombardment_dest_picker_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_ice_bombardment_dest_picker_SpellScript(); + } +}; + +void AddSC_boss_ahune() +{ + new boss_ahune(); + new npc_frozen_core(); + new npc_earthen_ring_flamecaller(); + new npc_ahune_bunny(); + new go_ahune_ice_stone(); + new spell_ahune_synch_health(); + new spell_summoning_rhyme_aura(); + new spell_summon_ice_spear_delayer(); + new spell_ice_spear_control_aura(); + new spell_slippery_floor_periodic(); + new spell_ahune_spanky_hands(); + new spell_ahune_minion_despawner(); + new spell_ice_spear_target_picker(); + new spell_ice_bombardment_dest_picker(); +} diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp index 87a07cd1e5e..0fac7b5a39d 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp @@ -31,15 +31,125 @@ class instance_the_slave_pens : public InstanceMapScript public: instance_the_slave_pens() : InstanceMapScript(SPScriptName, 547) { } + struct instance_the_slave_pens_InstanceMapScript : public InstanceScript + { + instance_the_slave_pens_InstanceMapScript(Map* map) : InstanceScript(map) + { + counter = DATA_FLAMECALLER_000; + } + + void OnCreatureCreate(Creature* creature) override + { + switch (creature->GetEntry()) + { + case NPC_AHUNE: + AhuneGUID = creature->GetGUID(); + break; + case NPC_FROZEN_CORE: + FrozenCoreGUID = creature->GetGUID(); + break; + case NPC_AHUNE_LOC_BUNNY: + AhuneBunnyGUID = creature->GetGUID(); + break; + case NPC_SHAMAN_BONFIRE_BUNNY_000: + BonfireBunnyGUIDs[0] = creature->GetGUID(); + break; + case NPC_SHAMAN_BONFIRE_BUNNY_001: + BonfireBunnyGUIDs[1] = creature->GetGUID(); + break; + case NPC_SHAMAN_BONFIRE_BUNNY_002: + BonfireBunnyGUIDs[2] = creature->GetGUID(); + break; + case NPC_SHAMAN_BEAM_BUNNY_000: + BeamBunnyGUIDs[0] = creature->GetGUID(); + break; + case NPC_SHAMAN_BEAM_BUNNY_001: + BeamBunnyGUIDs[1] = creature->GetGUID(); + break; + case NPC_SHAMAN_BEAM_BUNNY_002: + BeamBunnyGUIDs[2] = creature->GetGUID(); + break; + case NPC_LUMA_SKYMOTHER: + LumaGUID = creature->GetGUID(); + break; + case NPC_EARTHEN_RING_FLAMECALLER: + SetGuidData(counter, creature->GetGUID()); + ++counter; + break; + default: + break; + } + } + + void SetGuidData(uint32 data, ObjectGuid guid) override + { + switch (data) + { + case DATA_FLAMECALLER_000: + FlameCallerGUIDs[0] = guid; + break; + case DATA_FLAMECALLER_001: + FlameCallerGUIDs[1] = guid; + break; + case DATA_FLAMECALLER_002: + FlameCallerGUIDs[2] = guid; + break; + default: + break; + } + } + + ObjectGuid GetGuidData(uint32 type) const override + { + switch (type) + { + case DATA_AHUNE: + return AhuneGUID; + case DATA_AHUNE_BUNNY: + return AhuneBunnyGUID; + case DATA_FROZEN_CORE: + return FrozenCoreGUID; + case DATA_FLAMECALLER_000: + return FlameCallerGUIDs[0]; + case DATA_FLAMECALLER_001: + return FlameCallerGUIDs[1]; + case DATA_FLAMECALLER_002: + return FlameCallerGUIDs[2]; + case DATA_BONFIRE_BUNNY_000: + return BonfireBunnyGUIDs[0]; + case DATA_BONFIRE_BUNNY_001: + return BonfireBunnyGUIDs[1]; + case DATA_BONFIRE_BUNNY_002: + return BonfireBunnyGUIDs[2]; + case DATA_BEAM_BUNNY_000: + return BeamBunnyGUIDs[0]; + case DATA_BEAM_BUNNY_001: + return BeamBunnyGUIDs[1]; + case DATA_BEAM_BUNNY_002: + return BeamBunnyGUIDs[2]; + case DATA_LUMA_SKYMOTHER: + return LumaGUID; + default: + break; + } + return ObjectGuid::Empty; + } + + protected: + ObjectGuid AhuneGUID; + ObjectGuid AhuneBunnyGUID; + ObjectGuid FrozenCoreGUID; + ObjectGuid LumaGUID; + ObjectGuid FlameCallerGUIDs[3]; + ObjectGuid BonfireBunnyGUIDs[3]; + ObjectGuid BeamBunnyGUIDs[3]; + uint8 counter; + }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_the_slave_pens_InstanceMapScript(map); } - - struct instance_the_slave_pens_InstanceMapScript : public InstanceScript - { - instance_the_slave_pens_InstanceMapScript(Map* map) : InstanceScript(map) { } - }; }; void AddSC_instance_the_slave_pens() diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h index 95e6e44121e..544e98fd206 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h @@ -27,7 +27,43 @@ enum DataTypes { DATA_MENNU_THE_BETRAYER = 1, DATA_ROKMAR_THE_CRACKLER = 2, - DATA_QUAGMIRRAN = 3 + DATA_QUAGMIRRAN = 3, + DATA_AHUNE = 4, + DATA_AHUNE_BUNNY = 5, + DATA_FROZEN_CORE = 6, + DATA_FLAMECALLER_000 = 7, + DATA_FLAMECALLER_001 = 8, + DATA_FLAMECALLER_002 = 9, + DATA_BONFIRE_BUNNY_000 = 10, + DATA_BONFIRE_BUNNY_001 = 11, + DATA_BONFIRE_BUNNY_002 = 12, + DATA_BEAM_BUNNY_000 = 13, + DATA_BEAM_BUNNY_001 = 14, + DATA_BEAM_BUNNY_002 = 15, + DATA_LUMA_SKYMOTHER = 16 +}; + +enum CreaturesIds +{ + NPC_AHUNE = 25740, + NPC_FROZEN_CORE = 25865, + NPC_LUMA_SKYMOTHER = 25697, + NPC_AHUNE_LOC_BUNNY = 25745, + NPC_EARTHEN_RING_FLAMECALLER = 25754, + NPC_SHAMAN_BONFIRE_BUNNY_000 = 25971, + NPC_SHAMAN_BONFIRE_BUNNY_001 = 25972, + NPC_SHAMAN_BONFIRE_BUNNY_002 = 25973, + NPC_SHAMAN_BEAM_BUNNY_000 = 25964, + NPC_SHAMAN_BEAM_BUNNY_001 = 25965, + NPC_SHAMAN_BEAM_BUNNY_002 = 25966, + NPC_WHISP_DEST_BUNNY = 26120, + NPC_WHISP_SOURCE_BUNNY = 26121 +}; + +enum GameObjectIds +{ + GO_ICE_SPEAR = 188077, + GO_ICE_STONE = 187882 }; #endif // SLAVE_PENS_H diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp index 4e20e6b0953..9b8220596c9 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp @@ -372,7 +372,7 @@ class boss_vazruden_the_herald : public CreatureScript if (summon->GetEntry() == NPC_NAZAN) { summon->SetDisableGravity(true); - summon->SetSpeed(MOVE_FLIGHT, 2.5f); + summon->SetSpeedRate(MOVE_FLIGHT, 2.5f); if (victim) AttackStartNoMove(victim); } diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp index 499550945c6..2592ed3b262 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp @@ -180,24 +180,23 @@ class boss_grand_warlock_nethekurse : public CreatureScript } void MoveInLineOfSight(Unit* who) override - { if (!IntroOnce && me->IsWithinDistInMap(who, 30.0f)) - { + { if (who->GetTypeId() != TYPEID_PLAYER) return; - Talk(SAY_INTRO); - IntroOnce = true; - IsIntroEvent = true; + Talk(SAY_INTRO); + IntroOnce = true; + IsIntroEvent = true; - instance->SetBossState(DATA_NETHEKURSE, IN_PROGRESS); - } + instance->SetBossState(DATA_NETHEKURSE, IN_PROGRESS); + } - if (IsIntroEvent || !IsMainEvent) - return; + if (IsIntroEvent || !IsMainEvent) + return; - ScriptedAI::MoveInLineOfSight(who); + ScriptedAI::MoveInLineOfSight(who); } void EnterCombat(Unit* /*who*/) override diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp index 4faab709e16..c29d560529d 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp @@ -109,7 +109,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript { removeAdds(); _Reset(); - me->SetSpeed(MOVE_RUN, 2); + me->SetSpeedRate(MOVE_RUN, 2); me->SetWalk(false); Initialize(); @@ -231,7 +231,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript { // stop bladedance InBlade = false; - me->SetSpeed(MOVE_RUN, 2); + me->SetSpeedRate(MOVE_RUN, 2); me->GetMotionMaster()->MoveChase(me->GetVictim()); Blade_Dance_Timer = 30000; Wait_Timer = 0; @@ -264,7 +264,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript Wait_Timer = 1; InBlade = true; Blade_Dance_Timer = 0; - me->SetSpeed(MOVE_RUN, 4); + me->SetSpeedRate(MOVE_RUN, 4); return; } else diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp index 102d567e810..20d96ecd29c 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp @@ -130,7 +130,7 @@ class boss_alar : public CreatureScript _Reset(); me->SetDisplayId(me->GetNativeDisplayId()); - me->SetSpeed(MOVE_RUN, DefaultMoveSpeedRate); + me->SetSpeedRate(MOVE_RUN, DefaultMoveSpeedRate); //me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 10); //me->SetFloatValue(UNIT_FIELD_COMBATREACH, 10); me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, true); @@ -178,7 +178,7 @@ class boss_alar : public CreatureScript me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->AttackStop(); me->SetTarget(ObjectGuid::Empty); - me->SetSpeed(MOVE_RUN, 5.0f); + me->SetSpeedRate(MOVE_RUN, 5.0f); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(0, waypoint[5][0], waypoint[5][1], waypoint[5][2]); } @@ -261,7 +261,7 @@ class boss_alar : public CreatureScript case WE_REVIVE: me->SetUInt32Value(UNIT_FIELD_BYTES_1, UNIT_STAND_STATE_STAND); me->SetFullHealth(); - me->SetSpeed(MOVE_RUN, DefaultMoveSpeedRate); + me->SetSpeedRate(MOVE_RUN, DefaultMoveSpeedRate); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); DoZoneInCombat(); DoCast(me, SPELL_REBIRTH, true); @@ -289,6 +289,7 @@ class boss_alar : public CreatureScript me->SetPosition(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.0f); me->StopMoving(); WaitEvent = WE_LAND; + return; } else { diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp index 9fd1c5c7388..30b3fd67687 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp @@ -325,86 +325,85 @@ class boss_high_astromancer_solarian : public CreatureScript else Phase1_Timer-=diff; } - else - if (Phase == 2) + else if (Phase == 2) + { + //10 seconds after Solarian disappears, 12 mobs spawn out of the three portals. + me->AttackStop(); + me->StopMoving(); + if (Phase2_Timer <= diff) { - //10 seconds after Solarian disappears, 12 mobs spawn out of the three portals. - me->AttackStop(); - me->StopMoving(); - if (Phase2_Timer <= diff) - { - Phase = 3; - for (int i=0; i <= 2; ++i) - for (int j=1; j <= 4; j++) - SummonMinion(NPC_SOLARIUM_AGENT, Portals[i][0], Portals[i][1], Portals[i][2]); + Phase = 3; + for (int i=0; i <= 2; ++i) + for (int j=1; j <= 4; j++) + SummonMinion(NPC_SOLARIUM_AGENT, Portals[i][0], Portals[i][1], Portals[i][2]); - Talk(SAY_SUMMON1); - Phase2_Timer = 10000; - } - else - Phase2_Timer -= diff; + Talk(SAY_SUMMON1); + Phase2_Timer = 10000; } else - if (Phase == 3) - { - me->AttackStop(); - me->StopMoving(); - //Check Phase3_Timer - if (Phase3_Timer <= diff) - { - Phase = 1; - //15 seconds later Solarian reappears out of one of the 3 portals. Simultaneously, 2 healers appear in the two other portals. - int i = rand32() % 3; - me->GetMotionMaster()->Clear(); - me->SetPosition(Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O); - - for (int j=0; j <= 2; j++) - if (j != i) - SummonMinion(NPC_SOLARIUM_PRIEST, Portals[j][0], Portals[j][1], Portals[j][2]); - - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetVisible(true); - - Talk(SAY_SUMMON2); - AppearDelay = true; - Phase3_Timer = 15000; - } - else - Phase3_Timer -= diff; - } - else - if (Phase == 4) - { - //Fear_Timer - if (Fear_Timer <= diff) - { - DoCast(me, SPELL_FEAR); - Fear_Timer = 20000; - } - else - Fear_Timer -= diff; - //VoidBolt_Timer - if (VoidBolt_Timer <= diff) - { - DoCastVictim(SPELL_VOID_BOLT); - VoidBolt_Timer = 10000; - } - else - VoidBolt_Timer -= diff; - } - //When Solarian reaches 20% she will transform into a huge void walker. - if (Phase != 4 && me->HealthBelowPct(20)) - { - Phase = 4; - //To make sure she wont be invisible or not selecatble - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - me->SetVisible(true); - Talk(SAY_VOIDA); - Talk(SAY_VOIDB); - me->SetArmor(WV_ARMOR); - me->SetDisplayId(MODEL_VOIDWALKER); - me->SetObjectScale(defaultsize*2.5f); - } + Phase2_Timer -= diff; + } + else if (Phase == 3) + { + me->AttackStop(); + me->StopMoving(); + //Check Phase3_Timer + if (Phase3_Timer <= diff) + { + Phase = 1; + //15 seconds later Solarian reappears out of one of the 3 portals. Simultaneously, 2 healers appear in the two other portals. + int i = rand32() % 3; + me->GetMotionMaster()->Clear(); + me->SetPosition(Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O); + + for (int j=0; j <= 2; j++) + if (j != i) + SummonMinion(NPC_SOLARIUM_PRIEST, Portals[j][0], Portals[j][1], Portals[j][2]); + + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + me->SetVisible(true); + + Talk(SAY_SUMMON2); + AppearDelay = true; + Phase3_Timer = 15000; + } + else + Phase3_Timer -= diff; + } + else if (Phase == 4) + { + //Fear_Timer + if (Fear_Timer <= diff) + { + DoCast(me, SPELL_FEAR); + Fear_Timer = 20000; + } + else + Fear_Timer -= diff; + //VoidBolt_Timer + if (VoidBolt_Timer <= diff) + { + DoCastVictim(SPELL_VOID_BOLT); + VoidBolt_Timer = 10000; + } + else + VoidBolt_Timer -= diff; + } + + //When Solarian reaches 20% she will transform into a huge void walker. + if (Phase != 4 && me->HealthBelowPct(20)) + { + Phase = 4; + //To make sure she wont be invisible or not selecatble + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + me->SetVisible(true); + Talk(SAY_VOIDA); + Talk(SAY_VOIDB); + me->SetArmor(WV_ARMOR); + me->SetDisplayId(MODEL_VOIDWALKER); + me->SetObjectScale(defaultsize*2.5f); + } + DoMeleeAttackIfReady(); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp index e5812390bd2..be27932e6b4 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp @@ -144,6 +144,7 @@ enum Spells // Thaladred the Darkener spells SPELL_PSYCHIC_BLOW = 10689, SPELL_SILENCE = 30225, + SPELL_REND = 36965, // Lord Sanguinar spells SPELL_BELLOWING_ROAR = 40636, // Grand Astromancer Capernian spells @@ -881,11 +882,13 @@ class boss_thaladred_the_darkener : public CreatureScript { Gaze_Timer = 100; Silence_Timer = 20000; + Rend_Timer = 4000; PsychicBlow_Timer = 10000; } uint32 Gaze_Timer; uint32 Silence_Timer; + uint32 Rend_Timer; uint32 PsychicBlow_Timer; void Reset() override @@ -939,6 +942,15 @@ class boss_thaladred_the_darkener : public CreatureScript else Silence_Timer -= diff; + //Rend_Timer + if (Rend_Timer <= diff) + { + DoCastVictim(SPELL_REND); + Rend_Timer = 4000; + } + else + Rend_Timer -= diff; + //PsychicBlow_Timer if (PsychicBlow_Timer <= diff) { diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp index 46388c3a185..edfa2aedf92 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp @@ -1,6 +1,5 @@ /* * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -16,13 +15,6 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -/* ScriptData -SDName: Boss_Void_Reaver -SD%Complete: 90 -SDComment: Should reset if raid are out of room. -SDCategory: Tempest Keep, The Eye -EndScriptData */ - #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_eye.h" @@ -43,10 +35,17 @@ enum Spells SPELL_BERSERK = 27680 }; +enum Events +{ + EVENT_POUNDING = 1, + EVENT_ARCANE_ORB, + EVENT_KNOCK_AWAY, + EVENT_BERSERK +}; + class boss_void_reaver : public CreatureScript { public: - boss_void_reaver() : CreatureScript("boss_void_reaver") { } struct boss_void_reaverAI : public BossAI @@ -58,21 +57,9 @@ class boss_void_reaver : public CreatureScript void Initialize() { - Pounding_Timer = 15000; - ArcaneOrb_Timer = 3000; - KnockAway_Timer = 30000; - Berserk_Timer = 600000; - Enraged = false; } - uint32 Pounding_Timer; - uint32 ArcaneOrb_Timer; - uint32 KnockAway_Timer; - uint32 Berserk_Timer; - - bool Enraged; - void Reset() override { Initialize(); @@ -95,71 +82,84 @@ class boss_void_reaver : public CreatureScript { Talk(SAY_AGGRO); _EnterCombat(); + + events.ScheduleEvent(EVENT_POUNDING, 15000); + events.ScheduleEvent(EVENT_ARCANE_ORB, 3000); + events.ScheduleEvent(EVENT_KNOCK_AWAY, 30000); + events.ScheduleEvent(EVENT_BERSERK, 600000); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; - // Pounding - if (Pounding_Timer <= diff) - { - DoCastVictim(SPELL_POUNDING); - Talk(SAY_POUNDING); - Pounding_Timer = 15000; //cast time(3000) + cooldown time(12000) - } - else - Pounding_Timer -= diff; - // Arcane Orb - if (ArcaneOrb_Timer <= diff) - { - Unit* target = NULL; - std::list<HostileReference*> t_list = me->getThreatManager().getThreatList(); - std::vector<Unit*> target_list; - for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) - { - target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); - if (!target) - continue; - // exclude pets & totems, 18 yard radius minimum - if (target->GetTypeId() == TYPEID_PLAYER && target->IsAlive() && !target->IsWithinDist(me, 18, false)) - target_list.push_back(target); - target = NULL; - } - if (!target_list.empty()) - target = *(target_list.begin() + rand32() % target_list.size()); - else - target = me->GetVictim(); + events.Update(diff); - if (target) - me->CastSpell(target, SPELL_ARCANE_ORB, false, NULL, NULL); - ArcaneOrb_Timer = 3000; - } - else - ArcaneOrb_Timer -= diff; - // Single Target knock back, reduces aggro - if (KnockAway_Timer <= diff) - { - DoCastVictim(SPELL_KNOCK_AWAY); - //Drop 25% aggro - if (DoGetThreat(me->GetVictim())) - DoModifyThreatPercent(me->GetVictim(), -25); - KnockAway_Timer = 30000; - } - else - KnockAway_Timer -= diff; - //Berserk - if (Berserk_Timer < diff && !Enraged) + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + while (uint32 eventId = events.ExecuteEvent()) { - DoCast(me, SPELL_BERSERK); - Enraged = true; + switch (eventId) + { + case EVENT_POUNDING: + DoCastVictim(SPELL_POUNDING); + Talk(SAY_POUNDING); + events.ScheduleEvent(EVENT_POUNDING, 15000); + break; + case EVENT_ARCANE_ORB: + { + Unit* target = NULL; + std::list<HostileReference*> t_list = me->getThreatManager().getThreatList(); + std::vector<Unit*> target_list; + for (std::list<HostileReference*>::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) + { + target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); + if (!target) + continue; + // exclude pets & totems, 18 yard radius minimum + if (target->GetTypeId() == TYPEID_PLAYER && target->IsAlive() && !target->IsWithinDist(me, 18, false)) + target_list.push_back(target); + target = NULL; + } + + if (!target_list.empty()) + target = *(target_list.begin() + rand32() % target_list.size()); + else + target = me->GetVictim(); + + if (target) + me->CastSpell(target, SPELL_ARCANE_ORB, false, NULL, NULL); + + events.ScheduleEvent(EVENT_ARCANE_ORB, 3000); + break; + } + case EVENT_KNOCK_AWAY: + DoCastVictim(SPELL_KNOCK_AWAY); + // Drop 25% aggro + if (DoGetThreat(me->GetVictim())) + DoModifyThreatPercent(me->GetVictim(), -25); + + events.ScheduleEvent(EVENT_KNOCK_AWAY, 30000); + break; + case EVENT_BERSERK: + if (!Enraged) + { + DoCast(me, SPELL_BERSERK); + Enraged = true; + } + break; + default: + break; + } } - else - Berserk_Timer -= diff; DoMeleeAttackIfReady(); } + + private: + bool Enraged; }; CreatureAI* GetAI(Creature* creature) const override diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp index 3aa2674aec6..d45e17bd28d 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp @@ -176,7 +176,7 @@ class npc_ragin_flames : public CreatureScript Initialize(); me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true); me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, true); - me->SetSpeed(MOVE_RUN, DUNGEON_MODE(0.5f, 0.7f)); + me->SetSpeedRate(MOVE_RUN, DUNGEON_MODE(0.5f, 0.7f)); } void EnterCombat(Unit* /*who*/) override diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp index cab5b9efbc3..f4ff9f7084c 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp @@ -537,7 +537,7 @@ class npc_zerekethvoidzone : public CreatureScript void Reset() override { - me->SetUInt32Value(UNIT_NPC_FLAGS, 0); + me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); me->setFaction(16); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp index 856649c6c5e..b9e7fb0034d 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp @@ -103,7 +103,7 @@ class npc_warp_splinter_treant : public CreatureScript { if (Unit* Warp = ObjectAccessor::GetUnit(*me, WarpGuid)) { - if (me->IsWithinMeleeRange(Warp, 2.5f)) + if (me->IsWithinMeleeRange(Warp)) { int32 CurrentHP_Treant = (int32)me->GetHealth(); Warp->CastCustomSpell(Warp, SPELL_HEAL_FATHER, &CurrentHP_Treant, 0, 0, true, 0, 0, me->GetGUID()); @@ -167,7 +167,7 @@ class boss_warp_splinter : public CreatureScript { Initialize(); - me->SetSpeed(MOVE_RUN, 0.7f, true); + me->SetSpeedRate(MOVE_RUN, 0.7f); } void EnterCombat(Unit* /*who*/) override diff --git a/src/server/scripts/Outland/outland_script_loader.cpp b/src/server/scripts/Outland/outland_script_loader.cpp new file mode 100644 index 00000000000..ed2c21da6c3 --- /dev/null +++ b/src/server/scripts/Outland/outland_script_loader.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +// Auchindoun - Auchenai Crypts +void AddSC_boss_shirrak_the_dead_watcher(); +void AddSC_boss_exarch_maladaar(); +void AddSC_instance_auchenai_crypts(); + +// Auchindoun - Mana Tombs +void AddSC_boss_pandemonius(); +void AddSC_boss_nexusprince_shaffar(); +void AddSC_instance_mana_tombs(); + +// Auchindoun - Sekketh Halls +void AddSC_boss_darkweaver_syth(); +void AddSC_boss_talon_king_ikiss(); +void AddSC_boss_anzu(); +void AddSC_instance_sethekk_halls(); + +// Auchindoun - Shadow Labyrinth +void AddSC_boss_ambassador_hellmaw(); +void AddSC_boss_blackheart_the_inciter(); +void AddSC_boss_grandmaster_vorpil(); +void AddSC_boss_murmur(); +void AddSC_instance_shadow_labyrinth(); + +// Black Temple +void AddSC_black_temple(); +void AddSC_boss_illidan(); +void AddSC_boss_shade_of_akama(); +void AddSC_boss_supremus(); +void AddSC_boss_gurtogg_bloodboil(); +void AddSC_boss_mother_shahraz(); +void AddSC_boss_reliquary_of_souls(); +void AddSC_boss_teron_gorefiend(); +void AddSC_boss_najentus(); +void AddSC_boss_illidari_council(); +void AddSC_instance_black_temple(); + +// Coilfang Reservoir - Serpent Shrine Cavern +void AddSC_boss_fathomlord_karathress(); +void AddSC_boss_hydross_the_unstable(); +void AddSC_boss_lady_vashj(); +void AddSC_boss_leotheras_the_blind(); +void AddSC_boss_morogrim_tidewalker(); +void AddSC_instance_serpentshrine_cavern(); +void AddSC_boss_the_lurker_below(); + +// Coilfang Reservoir - The Steam Vault +void AddSC_boss_hydromancer_thespia(); +void AddSC_boss_mekgineer_steamrigger(); +void AddSC_boss_warlord_kalithresh(); +void AddSC_instance_steam_vault(); + +// Coilfang Reservoir - The Slave Pens +void AddSC_instance_the_slave_pens(); +void AddSC_boss_mennu_the_betrayer(); +void AddSC_boss_rokmar_the_crackler(); +void AddSC_boss_quagmirran(); +void AddSC_boss_ahune(); + +// Coilfang Reservoir - The Underbog +void AddSC_instance_the_underbog(); +void AddSC_boss_hungarfen(); +void AddSC_boss_the_black_stalker(); + +// Gruul's Lair +void AddSC_boss_gruul(); +void AddSC_boss_high_king_maulgar(); +void AddSC_instance_gruuls_lair(); +void AddSC_boss_broggok(); //HC Blood Furnace +void AddSC_boss_kelidan_the_breaker(); +void AddSC_boss_the_maker(); +void AddSC_instance_blood_furnace(); +void AddSC_boss_magtheridon(); //HC Magtheridon's Lair +void AddSC_instance_magtheridons_lair(); +void AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls +void AddSC_boss_warbringer_omrogg(); +void AddSC_boss_warchief_kargath_bladefist(); +void AddSC_shattered_halls(); +void AddSC_instance_shattered_halls(); +void AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts +void AddSC_boss_omor_the_unscarred(); +void AddSC_boss_vazruden_the_herald(); +void AddSC_instance_ramparts(); +void AddSC_arcatraz(); //TK Arcatraz +void AddSC_boss_zereketh_the_unbound(); +void AddSC_boss_dalliah_the_doomsayer(); +void AddSC_boss_wrath_scryer_soccothrates(); +void AddSC_boss_harbinger_skyriss(); +void AddSC_instance_arcatraz(); +void AddSC_boss_high_botanist_freywinn(); //TK Botanica +void AddSC_boss_laj(); +void AddSC_boss_warp_splinter(); +void AddSC_boss_thorngrin_the_tender(); +void AddSC_boss_commander_sarannis(); +void AddSC_instance_the_botanica(); +void AddSC_boss_alar(); //TK The Eye +void AddSC_boss_kaelthas(); +void AddSC_boss_void_reaver(); +void AddSC_boss_high_astromancer_solarian(); +void AddSC_instance_the_eye(); +void AddSC_the_eye(); +void AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar +void AddSC_boss_gatewatcher_gyrokill(); +void AddSC_boss_nethermancer_sepethrea(); +void AddSC_boss_pathaleon_the_calculator(); +void AddSC_boss_mechano_lord_capacitus(); +void AddSC_instance_mechanar(); + +void AddSC_blades_edge_mountains(); +void AddSC_boss_doomlordkazzak(); +void AddSC_boss_doomwalker(); +void AddSC_hellfire_peninsula(); +void AddSC_nagrand(); +void AddSC_netherstorm(); +void AddSC_shadowmoon_valley(); +void AddSC_shattrath_city(); +void AddSC_terokkar_forest(); +void AddSC_zangarmarsh(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddOutlandScripts() +{ + // Auchindoun - Auchenai Crypts + AddSC_boss_shirrak_the_dead_watcher(); + AddSC_boss_exarch_maladaar(); + AddSC_instance_auchenai_crypts(); + + // Auchindoun - Mana Tombs + AddSC_boss_pandemonius(); + AddSC_boss_nexusprince_shaffar(); + AddSC_instance_mana_tombs(); + + // Auchindoun - Sekketh Halls + AddSC_boss_darkweaver_syth(); + AddSC_boss_talon_king_ikiss(); + AddSC_boss_anzu(); + AddSC_instance_sethekk_halls(); + + // Auchindoun - Shadow Labyrinth + AddSC_boss_ambassador_hellmaw(); + AddSC_boss_blackheart_the_inciter(); + AddSC_boss_grandmaster_vorpil(); + AddSC_boss_murmur(); + AddSC_instance_shadow_labyrinth(); + + // Black Temple + AddSC_black_temple(); + AddSC_boss_illidan(); + AddSC_boss_shade_of_akama(); + AddSC_boss_supremus(); + AddSC_boss_gurtogg_bloodboil(); + AddSC_boss_mother_shahraz(); + AddSC_boss_reliquary_of_souls(); + AddSC_boss_teron_gorefiend(); + AddSC_boss_najentus(); + AddSC_boss_illidari_council(); + AddSC_instance_black_temple(); + + // Coilfang Reservoir - Serpent Shrine Cavern + AddSC_boss_fathomlord_karathress(); + AddSC_boss_hydross_the_unstable(); + AddSC_boss_lady_vashj(); + AddSC_boss_leotheras_the_blind(); + AddSC_boss_morogrim_tidewalker(); + AddSC_instance_serpentshrine_cavern(); + AddSC_boss_the_lurker_below(); + + // Coilfang Reservoir - The Steam Vault + AddSC_instance_steam_vault(); + AddSC_boss_hydromancer_thespia(); + AddSC_boss_mekgineer_steamrigger(); + AddSC_boss_warlord_kalithresh(); + + // Coilfang Reservoir - The Slave Pens + AddSC_instance_the_slave_pens(); + AddSC_boss_mennu_the_betrayer(); + AddSC_boss_rokmar_the_crackler(); + AddSC_boss_quagmirran(); + AddSC_boss_ahune(); + + // Coilfang Reservoir - The Underbog + AddSC_instance_the_underbog(); + AddSC_boss_hungarfen(); + AddSC_boss_the_black_stalker(); + + // Gruul's Lair + AddSC_boss_gruul(); + AddSC_boss_high_king_maulgar(); + AddSC_instance_gruuls_lair(); + AddSC_boss_broggok(); //HC Blood Furnace + AddSC_boss_kelidan_the_breaker(); + AddSC_boss_the_maker(); + AddSC_instance_blood_furnace(); + AddSC_boss_magtheridon(); //HC Magtheridon's Lair + AddSC_instance_magtheridons_lair(); + AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls + AddSC_boss_warbringer_omrogg(); + AddSC_boss_warchief_kargath_bladefist(); + AddSC_shattered_halls(); + AddSC_instance_shattered_halls(); + AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts + AddSC_boss_omor_the_unscarred(); + AddSC_boss_vazruden_the_herald(); + AddSC_instance_ramparts(); + AddSC_arcatraz(); //TK Arcatraz + AddSC_boss_zereketh_the_unbound(); + AddSC_boss_dalliah_the_doomsayer(); + AddSC_boss_wrath_scryer_soccothrates(); + AddSC_boss_harbinger_skyriss(); + AddSC_instance_arcatraz(); + AddSC_boss_high_botanist_freywinn(); //TK Botanica + AddSC_boss_laj(); + AddSC_boss_warp_splinter(); + AddSC_boss_thorngrin_the_tender(); + AddSC_boss_commander_sarannis(); + AddSC_instance_the_botanica(); + AddSC_boss_alar(); //TK The Eye + AddSC_boss_kaelthas(); + AddSC_boss_void_reaver(); + AddSC_boss_high_astromancer_solarian(); + AddSC_instance_the_eye(); + AddSC_the_eye(); + AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar + AddSC_boss_gatewatcher_gyrokill(); + AddSC_boss_nethermancer_sepethrea(); + AddSC_boss_pathaleon_the_calculator(); + AddSC_boss_mechano_lord_capacitus(); + AddSC_instance_mechanar(); + + AddSC_blades_edge_mountains(); + AddSC_boss_doomlordkazzak(); + AddSC_boss_doomwalker(); + AddSC_hellfire_peninsula(); + AddSC_nagrand(); + AddSC_netherstorm(); + AddSC_shadowmoon_valley(); + AddSC_shattrath_city(); + AddSC_terokkar_forest(); + AddSC_zangarmarsh(); +} diff --git a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp index 30bf085be43..9074f1ea373 100644 --- a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp +++ b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp @@ -959,7 +959,7 @@ public: { // Spell 37392 does not exist in dbc, manually spawning me->SummonCreature(NPC_OSCILLATING_FREQUENCY_SCANNER_TOP_BUNNY, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + 0.5f, me->GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 50000); - me->SummonGameObject(GO_OSCILLATING_FREQUENCY_SCANNER, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation(), 0, 0, 0, 0, 50); + me->SummonGameObject(GO_OSCILLATING_FREQUENCY_SCANNER, *me, G3D::Quat(), 50); me->DespawnOrUnsummon(50000); } diff --git a/src/server/scripts/Outland/zone_hellfire_peninsula.cpp b/src/server/scripts/Outland/zone_hellfire_peninsula.cpp index 404cdc7ceb2..668c484dd63 100644 --- a/src/server/scripts/Outland/zone_hellfire_peninsula.cpp +++ b/src/server/scripts/Outland/zone_hellfire_peninsula.cpp @@ -159,7 +159,7 @@ public: else TC_LOG_ERROR("scripts", "TRINITY: npc_ancestral_wolf can not obtain owner or owner is not a player."); - creature->SetSpeed(MOVE_WALK, 1.5f); + creature->SetSpeedRate(MOVE_WALK, 1.5f); Reset(); } @@ -192,7 +192,7 @@ public: if (ryga->IsAlive() && !ryga->IsInCombat()) { ryga->SetWalk(true); - ryga->SetSpeed(MOVE_WALK, 1.5f); + ryga->SetSpeedRate(MOVE_WALK, 1.5f); ryga->GetMotionMaster()->MovePoint(0, 517.340698f, 3885.03975f, 190.455978f, true); Reset(); } @@ -778,7 +778,7 @@ public: me->AddAura(SPELL_JULES_THREATENS_AURA, me); me->SetCanFly(true); - me->SetSpeed(MOVE_RUN, 0.2f); + me->SetSpeedRate(MOVE_RUN, 0.2f); me->SetFacingTo(3.207566f); me->GetMotionMaster()->MoveJump(exorcismPos[2], 2.0f, 2.0f); @@ -798,7 +798,7 @@ public: break; case ACTION_JULES_MOVE_HOME: wpreached = false; - me->SetSpeed(MOVE_RUN, 1.0f); + me->SetSpeedRate(MOVE_RUN, 1.0f); me->GetMotionMaster()->MovePoint(11, exorcismPos[2]); events.CancelEvent(EVENT_SUMMON_SKULL); diff --git a/src/server/scripts/Outland/zone_netherstorm.cpp b/src/server/scripts/Outland/zone_netherstorm.cpp index d35dedb5d27..8803ce9d9ed 100644 --- a/src/server/scripts/Outland/zone_netherstorm.cpp +++ b/src/server/scripts/Outland/zone_netherstorm.cpp @@ -19,7 +19,7 @@ /* ScriptData SDName: Netherstorm SD%Complete: 80 -SDComment: Quest support: 10337, 10438, 10652 (special flight paths), 10198, 10191 +SDComment: Quest support: 10337, 10652 (special flight paths), 10198, 10191 SDCategory: Netherstorm EndScriptData */ @@ -335,56 +335,6 @@ public: }; /*###### -## npc_professor_dabiri -######*/ -enum ProfessorDabiriData -{ - SPELL_PHASE_DISTRUPTOR = 35780, - - //WHISPER_DABIRI = 0, not existing in database - - QUEST_DIMENSIUS = 10439, - QUEST_ON_NETHERY_WINGS = 10438, -}; - -#define GOSSIP_ITEM "I need a new phase distruptor, Professor" - -class npc_professor_dabiri : public CreatureScript -{ -public: - npc_professor_dabiri() : CreatureScript("npc_professor_dabiri") { } - - //OnQuestAccept: - //if (quest->GetQuestId() == QUEST_DIMENSIUS) - //creature->AI()->Talk(WHISPER_DABIRI, player); - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - { - creature->CastSpell(player, SPELL_PHASE_DISTRUPTOR, false); - player->CLOSE_GOSSIP_MENU(); - } - - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_ON_NETHERY_WINGS) == QUEST_STATUS_INCOMPLETE && !player->HasItemCount(29778)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - -/*###### ## npc_phase_hunter ######*/ @@ -752,7 +702,6 @@ void AddSC_netherstorm() { new npc_commander_dawnforge(); new at_commander_dawnforge(); - new npc_professor_dabiri(); new npc_phase_hunter(); new npc_bessy(); new npc_maxx_a_million_escort(); diff --git a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp index 7ea87a3c0c4..c91e5c94ca0 100644 --- a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp +++ b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp @@ -19,7 +19,7 @@ /* ScriptData SDName: Shadowmoon_Valley SD%Complete: 100 -SDComment: Quest support: 10583, 10601, 10804, 10854, 10458, 10481, 10480, 10781, 10451. Vendor Drake Dealer Hurlunk. +SDComment: Quest support: 10804, 10854, 10458, 10481, 10480, 10781, 10451. SDCategory: Shadowmoon Valley EndScriptData */ @@ -28,9 +28,6 @@ npc_invis_infernal_caster npc_infernal_attacker npc_mature_netherwing_drake npc_enslaved_netherwing_drake -npc_drake_dealer_hurlunk -npcs_flanis_swiftwing_and_kagrosh -npc_karynaku npc_earthmender_wilda npc_torloth_the_magnificent npc_illidari_spawn @@ -90,8 +87,10 @@ public: void SummonInfernal() { - Creature* infernal = me->SummonCreature(NPC_INFERNAL_ATTACKER, me->GetPositionX(), me->GetPositionY(), ground + 0.05f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); - infernalGUID = infernal->GetGUID(); + if (Creature* infernal = me->SummonCreature(NPC_INFERNAL_ATTACKER, me->GetPositionX(), me->GetPositionY(), ground + 0.05f, 0.0f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000)) + infernalGUID = infernal->GetGUID(); + else + infernalGUID = ObjectGuid::Empty; } void UpdateAI(uint32 diff) override @@ -568,117 +567,6 @@ public: }; }; -/*###### -## npc_drake_dealer_hurlunk -######*/ - -class npc_drake_dealer_hurlunk : public CreatureScript -{ -public: - npc_drake_dealer_hurlunk() : CreatureScript("npc_drake_dealer_hurlunk") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_TRADE) - player->GetSession()->SendListInventory(creature->GetGUID()); - - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsVendor() && player->GetReputationRank(1015) == REP_EXALTED) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - -/*###### -## npc_flanis_swiftwing_and_kagrosh -######*/ - -#define GOSSIP_HSK1 "Take Flanis's Pack" -#define GOSSIP_HSK2 "Take Kagrosh's Pack" - -class npcs_flanis_swiftwing_and_kagrosh : public CreatureScript -{ -public: - npcs_flanis_swiftwing_and_kagrosh() : CreatureScript("npcs_flanis_swiftwing_and_kagrosh") { } - - bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - { - ItemPosCountVec dest; - uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 30658, 1, NULL); - if (msg == EQUIP_ERR_OK) - { - player->StoreNewItem(dest, 30658, true); - player->PlayerTalkClass->ClearMenus(); - } - } - if (action == GOSSIP_ACTION_INFO_DEF+2) - { - ItemPosCountVec dest; - uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 30659, 1, NULL); - if (msg == EQUIP_ERR_OK) - { - player->StoreNewItem(dest, 30659, true); - player->PlayerTalkClass->ClearMenus(); - } - } - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (player->GetQuestStatus(10583) == QUEST_STATUS_INCOMPLETE && !player->HasItemCount(30658, 1, true)) - player->ADD_GOSSIP_ITEM(0, GOSSIP_HSK1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - if (player->GetQuestStatus(10601) == QUEST_STATUS_INCOMPLETE && !player->HasItemCount(30659, 1, true)) - player->ADD_GOSSIP_ITEM(0, GOSSIP_HSK2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - -/*###### -# npc_karynaku -####*/ - -enum Karynaku -{ - QUEST_ALLY_OF_NETHER = 10870, - QUEST_ZUHULED_THE_WACK = 10866, - - NPC_ZUHULED_THE_WACKED = 11980, - - TAXI_PATH_ID = 649, -}; - -class npc_karynaku : public CreatureScript -{ - public: - npc_karynaku() : CreatureScript("npc_karynaku") { } - - bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override - { - if (quest->GetQuestId() == QUEST_ALLY_OF_NETHER) - player->ActivateTaxiPathTo(TAXI_PATH_ID); - - if (quest->GetQuestId() == QUEST_ZUHULED_THE_WACK) - creature->SummonCreature(NPC_ZUHULED_THE_WACKED, -4204.94f, 316.397f, 122.508f, 1.309f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 300000); - - return true; - } -}; - /*#### # npc_earthmender_wilda ####*/ @@ -1701,9 +1589,6 @@ void AddSC_shadowmoon_valley() new npc_mature_netherwing_drake(); new npc_enslaved_netherwing_drake(); new npc_dragonmaw_peon(); - new npc_drake_dealer_hurlunk(); - new npcs_flanis_swiftwing_and_kagrosh(); - new npc_karynaku(); new npc_earthmender_wilda(); new npc_lord_illidan_stormrage(); new go_crystal_prison(); diff --git a/src/server/scripts/Outland/zone_shattrath_city.cpp b/src/server/scripts/Outland/zone_shattrath_city.cpp index c734d000077..e4e51a98348 100644 --- a/src/server/scripts/Outland/zone_shattrath_city.cpp +++ b/src/server/scripts/Outland/zone_shattrath_city.cpp @@ -29,7 +29,6 @@ npc_salsalabim npc_shattrathflaskvendors npc_zephyr npc_kservant -npc_ishanah EndContentData */ #include "ScriptMgr.h" @@ -43,13 +42,15 @@ EndContentData */ ## npc_raliq_the_drunk ######*/ -#define GOSSIP_RALIQ "You owe Sim'salabim money. Hand them over or die!" - -enum Raliq +enum RaliqTheDrunk { - SPELL_UPPERCUT = 10966, - QUEST_CRACK_SKULLS = 10009, - FACTION_HOSTILE_RD = 45 + SAY_RALIQ_ATTACK = 0, + OPTION_ID_COLLECT_A_DEBT = 0, + FACTION_OGRE_HOSTILE = 45, + MENU_ID_COLLECT_A_DEBT = 7729, + NPC_TEXT_WUT_YOU_WANT = 9440, + CRACKIN_SOME_SKULLS = 10009, + SPELL_UPPERCUT = 10966 }; class npc_raliq_the_drunk : public CreatureScript @@ -63,7 +64,8 @@ public: if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); - creature->setFaction(FACTION_HOSTILE_RD); + creature->setFaction(FACTION_OGRE_HOSTILE); + creature->AI()->Talk(SAY_RALIQ_ATTACK, player); creature->AI()->AttackStart(player); } return true; @@ -71,10 +73,16 @@ public: bool OnGossipHello(Player* player, Creature* creature) override { - if (player->GetQuestStatus(QUEST_CRACK_SKULLS) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_RALIQ, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - - player->SEND_GOSSIP_MENU(9440, creature->GetGUID()); + if (player->GetQuestStatus(CRACKIN_SOME_SKULLS) == QUEST_STATUS_INCOMPLETE) + { + player->ADD_GOSSIP_ITEM_DB(MENU_ID_COLLECT_A_DEBT, OPTION_ID_COLLECT_A_DEBT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + player->SEND_GOSSIP_MENU(NPC_TEXT_WUT_YOU_WANT, creature->GetGUID()); + } + else + { + player->PlayerTalkClass->ClearMenus(); + player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); + } return true; } @@ -125,16 +133,14 @@ public: enum Salsalabim { - // Factions - FACTION_HOSTILE_SA = 90, - FACTION_FRIENDLY_SA = 35, - - // Quests - QUEST_10004 = 10004, - - // Spells - SPELL_MAGNETIC_PULL = 31705 - + SAY_DEMONIC_AGGRO = 0, + OPTION_ID_ALTRUIS_SENT_ME = 0, + FACTION_FRIENDLY = 35, + FACTION_DEMON_HOSTILE = 90, + MENU_ID_ALTRUIS_SENT_ME = 7725, + NPC_TEXT_SAL_GROWLS_AT_YOU = 9435, + PATIENCE_AND_UNDERSTANDING = 10004, + SPELL_MAGNETIC_PULL = 31705 }; class npc_salsalabim : public CreatureScript @@ -142,13 +148,26 @@ class npc_salsalabim : public CreatureScript public: npc_salsalabim() : CreatureScript("npc_salsalabim") { } - bool OnGossipHello(Player* player, Creature* creature) override + bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override { - if (player->GetQuestStatus(QUEST_10004) == QUEST_STATUS_INCOMPLETE) + player->PlayerTalkClass->ClearMenus(); + if (action == GOSSIP_ACTION_INFO_DEF+1) { - creature->setFaction(FACTION_HOSTILE_SA); + player->CLOSE_GOSSIP_MENU(); + creature->setFaction(FACTION_DEMON_HOSTILE); + creature->AI()->Talk(SAY_DEMONIC_AGGRO, player); creature->AI()->AttackStart(player); } + return true; + } + + bool OnGossipHello(Player* player, Creature* creature) override + { + if (player->GetQuestStatus(PATIENCE_AND_UNDERSTANDING) == QUEST_STATUS_INCOMPLETE) + { + player->ADD_GOSSIP_ITEM_DB(MENU_ID_ALTRUIS_SENT_ME, OPTION_ID_ALTRUIS_SENT_ME, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + player->SEND_GOSSIP_MENU(NPC_TEXT_SAL_GROWLS_AT_YOU, creature->GetGUID()); + } else { if (creature->IsQuestGiver()) @@ -187,7 +206,7 @@ public: { if (done_by->GetTypeId() == TYPEID_PLAYER && me->HealthBelowPctDamaged(20, damage)) { - done_by->ToPlayer()->GroupEventHappens(QUEST_10004, me); + done_by->ToPlayer()->GroupEventHappens(PATIENCE_AND_UNDERSTANDING, me); damage = 0; EnterEvadeMode(); } @@ -220,6 +239,19 @@ Purchase requires exalted reputation with Scryers/Aldor, Cenarion Expedition and ################################################## */ +enum FlaskVendors +{ + ALDOR_REPUTATION = 932, + SCRYERS_REPUTATION = 934, + THE_SHA_TAR_REPUTATION = 935, + CENARION_EXPEDITION_REP = 942, + NPC_TEXT_EXALTED_ALDOR = 11083, // (need to be exalted with Sha'tar, Cenarion Expedition and the Aldor) + NPC_TEXT_EXALTED_SCRYERS = 11084, // (need to be exalted with Sha'tar, Cenarion Expedition and the Scryers) + NPC_TEXT_WELCOME_NAME = 11085, // Access granted + ARCANIST_XORITH = 23483, // Scryer Apothecary + HALDOR_THE_COMPULSIVE = 23484 // Aldor Apothecary +}; + class npc_shattrathflaskvendors : public CreatureScript { public: @@ -236,31 +268,31 @@ public: bool OnGossipHello(Player* player, Creature* creature) override { - if (creature->GetEntry() == 23484) + if (creature->GetEntry() == HALDOR_THE_COMPULSIVE) { // Aldor vendor - if (creature->IsVendor() && (player->GetReputationRank(932) == REP_EXALTED) && (player->GetReputationRank(935) == REP_EXALTED) && (player->GetReputationRank(942) == REP_EXALTED)) + if (creature->IsVendor() && (player->GetReputationRank(ALDOR_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(THE_SHA_TAR_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(CENARION_EXPEDITION_REP) == REP_EXALTED)) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); - player->SEND_GOSSIP_MENU(11085, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_WELCOME_NAME, creature->GetGUID()); } else { - player->SEND_GOSSIP_MENU(11083, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_EXALTED_ALDOR, creature->GetGUID()); } } - if (creature->GetEntry() == 23483) + if (creature->GetEntry() == ARCANIST_XORITH) { // Scryers vendor - if (creature->IsVendor() && (player->GetReputationRank(934) == REP_EXALTED) && (player->GetReputationRank(935) == REP_EXALTED) && (player->GetReputationRank(942) == REP_EXALTED)) + if (creature->IsVendor() && (player->GetReputationRank(SCRYERS_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(THE_SHA_TAR_REPUTATION) == REP_EXALTED) && (player->GetReputationRank(CENARION_EXPEDITION_REP) == REP_EXALTED)) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); - player->SEND_GOSSIP_MENU(11085, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_WELCOME_NAME, creature->GetGUID()); } else { - player->SEND_GOSSIP_MENU(11084, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_EXALTED_SCRYERS, creature->GetGUID()); } } @@ -272,7 +304,13 @@ public: # npc_zephyr ######*/ -#define GOSSIP_HZ "Take me to the Caverns of Time." +enum Zephyr +{ + OPTION_ID_TAKE_ME_TO_C_O_T = 0, + KEEPERS_OF_TIME_REPUTATION = 989, + MENU_ID_TAKE_ME_TO_C_O_T = 9205, + TELEPORT_CAVERNS_OF_TIME = 37778 +}; class npc_zephyr : public CreatureScript { @@ -283,15 +321,15 @@ public: { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF+1) - player->CastSpell(player, 37778, false); + player->CastSpell(player, TELEPORT_CAVERNS_OF_TIME, false); return true; } bool OnGossipHello(Player* player, Creature* creature) override { - if (player->GetReputationRank(989) >= REP_REVERED) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HZ, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + if (player->GetReputationRank(KEEPERS_OF_TIME_REPUTATION) >= REP_REVERED) + player->ADD_GOSSIP_ITEM_DB(MENU_ID_TAKE_ME_TO_C_O_T, OPTION_ID_TAKE_ME_TO_C_O_T, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); @@ -305,28 +343,29 @@ public: enum KServant { - SAY1 = 0, - WHISP1 = 1, - WHISP2 = 2, - WHISP3 = 3, - WHISP4 = 4, - WHISP5 = 5, - WHISP6 = 6, - WHISP7 = 7, - WHISP8 = 8, - WHISP9 = 9, - WHISP10 = 10, - WHISP11 = 11, - WHISP12 = 12, - WHISP13 = 13, - WHISP14 = 14, - WHISP15 = 15, - WHISP16 = 16, - WHISP17 = 17, - WHISP18 = 18, - WHISP19 = 19, - WHISP20 = 20, - WHISP21 = 21 + SAY1 = 0, + WHISP1 = 1, + WHISP2 = 2, + WHISP3 = 3, + WHISP4 = 4, + WHISP5 = 5, + WHISP6 = 6, + WHISP7 = 7, + WHISP8 = 8, + WHISP9 = 9, + WHISP10 = 10, + WHISP11 = 11, + WHISP12 = 12, + WHISP13 = 13, + WHISP14 = 14, + WHISP15 = 15, + WHISP16 = 16, + WHISP17 = 17, + WHISP18 = 18, + WHISP19 = 19, + WHISP20 = 20, + WHISP21 = 21, + CITY_OF_LIGHT = 10211 }; class npc_kservant : public CreatureScript @@ -417,7 +456,7 @@ public: break; case 56: Talk(WHISP21, player); - player->GroupEventHappens(10211, me); + player->GroupEventHappens(CITY_OF_LIGHT, me); break; } } @@ -429,7 +468,7 @@ public: return; Player* player = who->ToPlayer(); - if (player && player->GetQuestStatus(10211) == QUEST_STATUS_INCOMPLETE) + if (player && player->GetQuestStatus(CITY_OF_LIGHT) == QUEST_STATUS_INCOMPLETE) { float Radius = 10.0f; if (me->IsWithinDistInMap(who, Radius)) @@ -443,43 +482,6 @@ public: }; }; -/*###### -# npc_ishanah -######*/ - -#define ISANAH_GOSSIP_1 "Who are the Sha'tar?" -#define ISANAH_GOSSIP_2 "Isn't Shattrath a draenei city? Why do you allow others here?" - -class npc_ishanah : public CreatureScript -{ -public: - npc_ishanah() : CreatureScript("npc_ishanah") { } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - player->SEND_GOSSIP_MENU(9458, creature->GetGUID()); - else if (action == GOSSIP_ACTION_INFO_DEF+2) - player->SEND_GOSSIP_MENU(9459, creature->GetGUID()); - - return true; - } - - bool OnGossipHello(Player* player, Creature* creature) override - { - if (creature->IsQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, ISANAH_GOSSIP_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, ISANAH_GOSSIP_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } -}; - void AddSC_shattrath_city() { new npc_raliq_the_drunk(); @@ -487,5 +489,4 @@ void AddSC_shattrath_city() new npc_shattrathflaskvendors(); new npc_zephyr(); new npc_kservant(); - new npc_ishanah(); } diff --git a/src/server/scripts/Outland/zone_terokkar_forest.cpp b/src/server/scripts/Outland/zone_terokkar_forest.cpp index 06a8af947b7..4b757544d65 100644 --- a/src/server/scripts/Outland/zone_terokkar_forest.cpp +++ b/src/server/scripts/Outland/zone_terokkar_forest.cpp @@ -27,7 +27,6 @@ EndScriptData */ npc_unkor_the_ruthless npc_infested_root_walker npc_rotting_forest_rager -npc_netherweb_victim npc_floon npc_isla_starmane npc_slim @@ -47,13 +46,13 @@ EndContentData */ enum UnkorTheRuthless { - SAY_SUBMIT = 0, - - FACTION_HOSTILE = 45, - FACTION_FRIENDLY = 35, - QUEST_DONTKILLTHEFATONE = 9889, - - SPELL_PULVERIZE = 2676 + SAY_SUBMIT = 0, + REQUIRED_KILL_COUNT = 10, + FACTION_FRIENDLY = 35, + FACTION_HOSTILE = 45, + SPELL_PULVERIZE = 2676, + QUEST_DONTKILLTHEFATONE = 9889, + NPC_BOULDERFIST_INVADER = 18260 }; class npc_unkor_the_ruthless : public CreatureScript @@ -117,7 +116,7 @@ public: Player* groupie = itr->GetSource(); if (groupie && groupie->GetQuestStatus(QUEST_DONTKILLTHEFATONE) == QUEST_STATUS_INCOMPLETE && - groupie->GetReqKillOrCastCurrentCount(QUEST_DONTKILLTHEFATONE, 18260) == 10) + groupie->GetReqKillOrCastCurrentCount(QUEST_DONTKILLTHEFATONE, NPC_BOULDERFIST_INVADER) == REQUIRED_KILL_COUNT) { groupie->AreaExploredOrEventHappens(QUEST_DONTKILLTHEFATONE); if (!CanDoQuest) @@ -126,7 +125,7 @@ public: } } else if (player->GetQuestStatus(QUEST_DONTKILLTHEFATONE) == QUEST_STATUS_INCOMPLETE && - player->GetReqKillOrCastCurrentCount(QUEST_DONTKILLTHEFATONE, 18260) == 10) + player->GetReqKillOrCastCurrentCount(QUEST_DONTKILLTHEFATONE, NPC_BOULDERFIST_INVADER) == REQUIRED_KILL_COUNT) { player->AreaExploredOrEventHappens(QUEST_DONTKILLTHEFATONE); CanDoQuest = true; @@ -171,6 +170,11 @@ public: ## npc_infested_root_walker ######*/ +enum InfestedRootWalker +{ + SPELL_SUMMON_WOOD_MITES = 39130 +}; + class npc_infested_root_walker : public CreatureScript { public: @@ -194,7 +198,7 @@ public: if (me->GetHealth() <= damage) if (rand32() % 100 < 75) //Summon Wood Mites - DoCast(me, 39130, true); + DoCast(me, SPELL_SUMMON_WOOD_MITES, true); } }; }; @@ -202,6 +206,12 @@ public: /*###### ## npc_skywing ######*/ + +enum Skywing +{ + QUEST_SKYWING = 10898 +}; + class npc_skywing : public CreatureScript { public: @@ -226,7 +236,7 @@ public: switch (waypointId) { case 8: - player->AreaExploredOrEventHappens(10898); + player->AreaExploredOrEventHappens(QUEST_SKYWING); break; } } @@ -240,7 +250,7 @@ public: return; Player* player = who->ToPlayer(); - if (player && player->GetQuestStatus(10898) == QUEST_STATUS_INCOMPLETE) + if (player && player->GetQuestStatus(QUEST_SKYWING) == QUEST_STATUS_INCOMPLETE) if (me->IsWithinDistInMap(who, 10.0f)) Start(false, false, who->GetGUID()); } @@ -258,6 +268,11 @@ public: ## npc_rotting_forest_rager ######*/ +enum RottingForestRager +{ + SPELL_SUMMON_LOTS_OF_WOOD_MITES = 39134 +}; + class npc_rotting_forest_rager : public CreatureScript { public: @@ -280,67 +295,8 @@ public: if (done_by->GetTypeId() == TYPEID_PLAYER) if (me->GetHealth() <= damage) if (rand32() % 100 < 75) - //Summon Lots of Wood Mights - DoCast(me, 39134, true); - } - }; -}; - -/*###### -## npc_netherweb_victim -######*/ - -enum NetherwebVictim -{ - QUEST_TARGET = 22459 - //SPELL_FREE_WEBBED = 38950 -}; - -const uint32 netherwebVictims[6] = -{ - 18470, 16805, 21242, 18452, 22482, 21285 -}; - -class npc_netherweb_victim : public CreatureScript -{ -public: - npc_netherweb_victim() : CreatureScript("npc_netherweb_victim") { } - - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_netherweb_victimAI(creature); - } - - struct npc_netherweb_victimAI : public ScriptedAI - { - npc_netherweb_victimAI(Creature* creature) : ScriptedAI(creature) { } - - void Reset() override { } - void EnterCombat(Unit* /*who*/) override { } - void MoveInLineOfSight(Unit* /*who*/) override { } - - - void JustDied(Unit* killer) override - { - Player* player = killer->ToPlayer(); - if (!player) - return; - - if (player->GetQuestStatus(10873) == QUEST_STATUS_INCOMPLETE) - { - if (rand32() % 100 < 25) - { - me->SummonCreature(QUEST_TARGET, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); - player->KilledMonsterCredit(QUEST_TARGET); - } - else - me->SummonCreature(netherwebVictims[rand32() % 6], 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); - - if (rand32() % 100 < 75) - me->SummonCreature(netherwebVictims[rand32() % 6], 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); - - me->SummonCreature(netherwebVictims[rand32() % 6], 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); - } + //Summon Lots of Wood Mites + DoCast(me, SPELL_SUMMON_LOTS_OF_WOOD_MITES, true); } }; }; @@ -349,19 +305,22 @@ public: ## npc_floon ######*/ -#define GOSSIP_FLOON1 "You owe Sim'salabim money. Hand them over or die!" -#define GOSSIP_FLOON2 "Hand over the money or die...again!" - enum Floon { - SAY_FLOON_ATTACK = 0, - - SPELL_SILENCE = 6726, - SPELL_FROSTBOLT = 9672, - SPELL_FROST_NOVA = 11831, - - FACTION_HOSTILE_FL = 1738, - QUEST_CRACK_SKULLS = 10009 + SAY_FLOON_ATTACK = 0, + OPTION_ID_PAY_UP_OR_DIE = 0, + OPTION_ID_COLLECT_A_DEBT = 0, + FACTION_HOSTILE_FLOON = 1738, + MENU_ID_PAY_UP_OR_DIE = 7731, + MENU_ID_COLLECT_A_DEBT = 7732, + GOSSIP_FLOON_STRANGE_SOUNDS = 9442, + GOSSIP_HE_ALREADY_KILLED_ME = 9443, + + SPELL_SILENCE = 6726, + SPELL_FROSTBOLT = 9672, + SPELL_FROST_NOVA = 11831, + + QUEST_CRACKIN_SOME_SKULLS = 10009 }; class npc_floon : public CreatureScript @@ -374,13 +333,13 @@ public: player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_INFO_DEF) { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FLOON2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(9443, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(MENU_ID_PAY_UP_OR_DIE, OPTION_ID_PAY_UP_OR_DIE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + player->SEND_GOSSIP_MENU(GOSSIP_HE_ALREADY_KILLED_ME, creature->GetGUID()); } if (action == GOSSIP_ACTION_INFO_DEF+1) { player->CLOSE_GOSSIP_MENU(); - creature->setFaction(FACTION_HOSTILE_FL); + creature->setFaction(FACTION_HOSTILE_FLOON); creature->AI()->Talk(SAY_FLOON_ATTACK, player); creature->AI()->AttackStart(player); } @@ -389,10 +348,10 @@ public: bool OnGossipHello(Player* player, Creature* creature) override { - if (player->GetQuestStatus(QUEST_CRACK_SKULLS) == QUEST_STATUS_INCOMPLETE) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FLOON1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); + if (player->GetQuestStatus(QUEST_CRACKIN_SOME_SKULLS) == QUEST_STATUS_INCOMPLETE) + player->ADD_GOSSIP_ITEM_DB(MENU_ID_COLLECT_A_DEBT, OPTION_ID_COLLECT_A_DEBT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(9442, creature->GetGUID()); + player->SEND_GOSSIP_MENU(GOSSIP_FLOON_STRANGE_SOUNDS, creature->GetGUID()); return true; } @@ -463,15 +422,16 @@ public: ######*/ enum IslaStarmaneData { - SAY_PROGRESS_1 = 0, - SAY_PROGRESS_2 = 1, - SAY_PROGRESS_3 = 2, - SAY_PROGRESS_4 = 3, - - QUEST_EFTW_H = 10052, - QUEST_EFTW_A = 10051, - GO_CAGE = 182794, - SPELL_CAT = 32447, + SAY_PROGRESS_1 = 0, + SAY_PROGRESS_2 = 1, + SAY_PROGRESS_3 = 2, + SAY_PROGRESS_4 = 3, + GO_DISTANCE = 10, + FACTION_ESCORTEE = 113, + ESCAPE_FROM_FIREWING_POINT_A = 10051, + ESCAPE_FROM_FIREWING_POINT_H = 10052, + SPELL_TRAVEL_FORM_CAT = 32447, + GO_CAGE = 182794 }; class npc_isla_starmane : public CreatureScript @@ -492,7 +452,7 @@ public: switch (waypointId) { case 0: - if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 10)) + if (GameObject* Cage = me->FindNearestGameObject(GO_CAGE, GO_DISTANCE)) Cage->SetGoState(GO_STATE_ACTIVE); break; case 2: @@ -507,16 +467,16 @@ public: case 29: Talk(SAY_PROGRESS_4, player); if (player->GetTeam() == ALLIANCE) - player->GroupEventHappens(QUEST_EFTW_A, me); + player->GroupEventHappens(ESCAPE_FROM_FIREWING_POINT_A, me); else if (player->GetTeam() == HORDE) - player->GroupEventHappens(QUEST_EFTW_H, me); + player->GroupEventHappens(ESCAPE_FROM_FIREWING_POINT_H, me); me->SetInFront(player); break; case 30: me->HandleEmoteCommand(EMOTE_ONESHOT_WAVE); break; case 31: - DoCast(me, SPELL_CAT); + DoCast(me, SPELL_TRAVEL_FORM_CAT); me->SetWalk(false); break; } @@ -532,19 +492,19 @@ public: if (Player* player = GetPlayerForEscort()) { if (player->GetTeam() == ALLIANCE) - player->FailQuest(QUEST_EFTW_A); + player->FailQuest(ESCAPE_FROM_FIREWING_POINT_A); else if (player->GetTeam() == HORDE) - player->FailQuest(QUEST_EFTW_H); + player->FailQuest(ESCAPE_FROM_FIREWING_POINT_H); } } }; bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override { - if (quest->GetQuestId() == QUEST_EFTW_H || quest->GetQuestId() == QUEST_EFTW_A) + if (quest->GetQuestId() == ESCAPE_FROM_FIREWING_POINT_H || quest->GetQuestId() == ESCAPE_FROM_FIREWING_POINT_A) { ENSURE_AI(npc_escortAI, (creature->AI()))->Start(true, false, player->GetGUID()); - creature->setFaction(113); + creature->setFaction(FACTION_ESCORTEE); } return true; } @@ -558,10 +518,20 @@ public: /*###### ## go_skull_pile ######*/ -#define GOSSIP_S_DARKSCREECHER_AKKARAI "Summon Darkscreecher Akkarai" -#define GOSSIP_S_KARROG "Summon Karrog" -#define GOSSIP_S_GEZZARAK_THE_HUNTRESS "Summon Gezzarak the Huntress" -#define GOSSIP_S_VAKKIZ_THE_WINDRAGER "Summon Vakkiz the Windrager" + +enum SkullPile +{ + OPTION_ID_GEZZARAK_THE_HUNTRESS = 0, + OPTION_ID_DARKSCREECHER_AKKARAI = 1, + OPTION_ID_KARROG = 2, + OPTION_ID_VAKKIZ_THE_WINDRAGER = 3, + GOSSIP_MENU_ID_SKULL_PILE = 8660, + ADVERSARIAL_BLOOD = 11885, + SUMMON_GEZZARAK_THE_HUNTRESS = 40632, + SUMMON_KARROG = 40640, + SUMMON_DARKSCREECHER_AKKARAI = 40642, + SUMMON_VAKKIZ_THE_WINDRAGER = 40644 +}; class go_skull_pile : public GameObjectScript { @@ -580,12 +550,12 @@ public: bool OnGossipHello(Player* player, GameObject* go) override { - if ((player->GetQuestStatus(11885) == QUEST_STATUS_INCOMPLETE) || player->GetQuestRewardStatus(11885)) + if ((player->GetQuestStatus(ADVERSARIAL_BLOOD) == QUEST_STATUS_INCOMPLETE) || player->GetQuestRewardStatus(ADVERSARIAL_BLOOD)) { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_S_DARKSCREECHER_AKKARAI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_S_KARROG, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_S_GEZZARAK_THE_HUNTRESS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_S_VAKKIZ_THE_WINDRAGER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_ID_SKULL_PILE, OPTION_ID_GEZZARAK_THE_HUNTRESS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_ID_SKULL_PILE, OPTION_ID_DARKSCREECHER_AKKARAI, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_ID_SKULL_PILE, OPTION_ID_KARROG, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_ID_SKULL_PILE, OPTION_ID_VAKKIZ_THE_WINDRAGER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); } player->SEND_GOSSIP_MENU(go->GetGOInfo()->questgiver.gossipID, go->GetGUID()); @@ -597,16 +567,16 @@ public: switch (action) { case GOSSIP_ACTION_INFO_DEF + 1: - player->CastSpell(player, 40642, false); + player->CastSpell(player, SUMMON_GEZZARAK_THE_HUNTRESS, false); break; case GOSSIP_ACTION_INFO_DEF + 2: - player->CastSpell(player, 40640, false); + player->CastSpell(player, SUMMON_DARKSCREECHER_AKKARAI, false); break; case GOSSIP_ACTION_INFO_DEF + 3: - player->CastSpell(player, 40632, false); + player->CastSpell(player, SUMMON_KARROG, false); break; case GOSSIP_ACTION_INFO_DEF + 4: - player->CastSpell(player, 40644, false); + player->CastSpell(player, SUMMON_VAKKIZ_THE_WINDRAGER, false); break; } } @@ -618,7 +588,9 @@ public: enum Slim { - FACTION_CONSORTIUM = 933 + FACTION_CONSORTIUM = 933, + NPC_TEXT_NEITHER_SLIM_NOR_SHADY = 9895, + NPC_TEXT_I_SEE_YOU_ARE_A_FRIEND = 9896 }; class npc_slim : public CreatureScript @@ -640,10 +612,10 @@ public: if (creature->IsVendor() && player->GetReputationRank(FACTION_CONSORTIUM) >= REP_FRIENDLY) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); - player->SEND_GOSSIP_MENU(9896, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_I_SEE_YOU_ARE_A_FRIEND, creature->GetGUID()); } else - player->SEND_GOSSIP_MENU(9895, creature->GetGUID()); + player->SEND_GOSSIP_MENU(NPC_TEXT_NEITHER_SLIM_NOR_SHADY, creature->GetGUID()); return true; } @@ -719,7 +691,6 @@ void AddSC_terokkar_forest() new npc_unkor_the_ruthless(); new npc_infested_root_walker(); new npc_rotting_forest_rager(); - new npc_netherweb_victim(); new npc_floon(); new npc_isla_starmane(); new go_skull_pile(); diff --git a/src/server/scripts/Pet/CMakeLists.txt b/src/server/scripts/Pet/CMakeLists.txt deleted file mode 100644 index 9ca268a9a3f..00000000000 --- a/src/server/scripts/Pet/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - Pet/pet_dk.cpp - Pet/pet_generic.cpp - Pet/pet_hunter.cpp - Pet/pet_mage.cpp - Pet/pet_priest.cpp - Pet/pet_shaman.cpp -) - -message(" -> Prepared: Pet") diff --git a/src/server/scripts/Pet/pet_dk.cpp b/src/server/scripts/Pet/pet_dk.cpp index 80b3a00774b..113b14a0d54 100644 --- a/src/server/scripts/Pet/pet_dk.cpp +++ b/src/server/scripts/Pet/pet_dk.cpp @@ -103,8 +103,8 @@ class npc_pet_dk_ebon_gargoyle : public CreatureScript //! HACK: Creature's can't have MOVEMENTFLAG_FLYING // Fly Away me->SetCanFly(true); - me->SetSpeed(MOVE_FLIGHT, 0.75f, true); - me->SetSpeed(MOVE_RUN, 0.75f, true); + me->SetSpeedRate(MOVE_FLIGHT, 0.75f); + me->SetSpeedRate(MOVE_RUN, 0.75f); float x = me->GetPositionX() + 20 * std::cos(me->GetOrientation()); float y = me->GetPositionY() + 20 * std::sin(me->GetOrientation()); float z = me->GetPositionZ() + 40; diff --git a/src/server/scripts/Pet/pet_generic.cpp b/src/server/scripts/Pet/pet_generic.cpp index 35455bc474b..ff57bc0415c 100644 --- a/src/server/scripts/Pet/pet_generic.cpp +++ b/src/server/scripts/Pet/pet_generic.cpp @@ -20,10 +20,239 @@ * Scriptnames of files in this file should be prefixed with "npc_pet_gen_". */ + /* ContentData + npc_pet_gen_baby_blizzard_bear 100% Baby Blizzard Bear sits down occasionally + npc_pet_gen_egbert 100% Egbert run's around + npc_pet_gen_pandaren_monk 100% Pandaren Monk drinks and bows with you + npc_pet_gen_mojo 100% Mojo follows you when you kiss it + EndContentData */ + #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "PassiveAI.h" #include "Player.h" +enum BabyBlizzardBearMisc +{ + SPELL_BBB_PET_SIT = 61853, + EVENT_BBB_PET_SIT = 1, + EVENT_BBB_PET_SIT_INTER = 2 +}; + +class npc_pet_gen_baby_blizzard_bear : public CreatureScript +{ +public: + npc_pet_gen_baby_blizzard_bear() : CreatureScript("npc_pet_gen_baby_blizzard_bear") {} + + struct npc_pet_gen_baby_blizzard_bearAI : public NullCreatureAI + { + npc_pet_gen_baby_blizzard_bearAI(Creature* creature) : NullCreatureAI(creature) + { + if (Unit* owner = me->GetCharmerOrOwner()) + me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle()); + _events.ScheduleEvent(EVENT_BBB_PET_SIT, urandms(10, 30)); + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + if (Unit* owner = me->GetCharmerOrOwner()) + if (!me->IsWithinDist(owner, 25.f)) + me->InterruptSpell(CURRENT_CHANNELED_SPELL); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_BBB_PET_SIT: + me->CastSpell(me, SPELL_BBB_PET_SIT, false); + _events.ScheduleEvent(EVENT_BBB_PET_SIT_INTER, urandms(15, 30)); + break; + case EVENT_BBB_PET_SIT_INTER: + me->InterruptSpell(CURRENT_CHANNELED_SPELL); + _events.ScheduleEvent(EVENT_BBB_PET_SIT, urandms(10, 30)); + break; + default: + break; + } + } + } + + private: + EventMap _events; + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new npc_pet_gen_baby_blizzard_bearAI(creature); + } +}; + +enum EgbertMisc +{ + SPELL_EGBERT = 40669, + EVENT_RETURN = 3 +}; + +class npc_pet_gen_egbert : public CreatureScript +{ +public: + npc_pet_gen_egbert() : CreatureScript("npc_pet_gen_egbert") {} + + struct npc_pet_gen_egbertAI : public NullCreatureAI + { + npc_pet_gen_egbertAI(Creature* creature) : NullCreatureAI(creature) + { + if (Unit* owner = me->GetCharmerOrOwner()) + if (owner->GetMap()->GetEntry()->addon > 1) + me->SetCanFly(true); + } + + void Reset() override + { + _events.Reset(); + if (Unit* owner = me->GetCharmerOrOwner()) + me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle()); + } + + void EnterEvadeMode(EvadeReason why) override + { + if (!_EnterEvadeMode(why)) + return; + + Reset(); + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + if (Unit* owner = me->GetCharmerOrOwner()) + { + if (!me->IsWithinDist(owner, 40.f)) + { + me->RemoveAura(SPELL_EGBERT); + me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle()); + } + } + + if (me->HasAura(SPELL_EGBERT)) + _events.ScheduleEvent(EVENT_RETURN, urandms(5, 20)); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_RETURN: + me->RemoveAura(SPELL_EGBERT); + break; + default: + break; + } + } + } + private: + EventMap _events; + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new npc_pet_gen_egbertAI(creature); + } +}; + +enum PandarenMonkMisc +{ + SPELL_PANDAREN_MONK = 69800, + EVENT_FOCUS = 1, + EVENT_EMOTE = 2, + EVENT_FOLLOW = 3, + EVENT_DRINK = 4 +}; + +class npc_pet_gen_pandaren_monk : public CreatureScript +{ +public: + npc_pet_gen_pandaren_monk() : CreatureScript("npc_pet_gen_pandaren_monk") {} + + struct npc_pet_gen_pandaren_monkAI : public NullCreatureAI + { + npc_pet_gen_pandaren_monkAI(Creature* creature) : NullCreatureAI(creature) { } + + void Reset() override + { + _events.Reset(); + _events.ScheduleEvent(EVENT_FOCUS, 1000); + } + + void EnterEvadeMode(EvadeReason why) override + { + if (!_EnterEvadeMode(why)) + return; + + Reset(); + } + + void ReceiveEmote(Player* /*player*/, uint32 emote) override + { + me->InterruptSpell(CURRENT_CHANNELED_SPELL); + me->StopMoving(); + + switch (emote) + { + case TEXT_EMOTE_BOW: + _events.ScheduleEvent(EVENT_FOCUS, 1000); + break; + case TEXT_EMOTE_DRINK: + _events.ScheduleEvent(EVENT_DRINK, 1000); + break; + } + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + if (Unit* owner = me->GetCharmerOrOwner()) + if (!me->IsWithinDist(owner, 30.f)) + me->InterruptSpell(CURRENT_CHANNELED_SPELL); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_FOCUS: + if (Unit* owner = me->GetCharmerOrOwner()) + me->SetFacingToObject(owner); + _events.ScheduleEvent(EVENT_EMOTE, 1000); + break; + case EVENT_EMOTE: + me->HandleEmoteCommand(EMOTE_ONESHOT_BOW); + _events.ScheduleEvent(EVENT_FOLLOW, 1000); + break; + case EVENT_FOLLOW: + if (Unit* owner = me->GetCharmerOrOwner()) + me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); + break; + case EVENT_DRINK: + me->CastSpell(me, SPELL_PANDAREN_MONK, false); + break; + default: + break; + } + } + } + private: + EventMap _events; + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new npc_pet_gen_pandaren_monkAI(creature); + } +}; + enum Mojo { SAY_MOJO = 0, @@ -89,5 +318,8 @@ class npc_pet_gen_mojo : public CreatureScript void AddSC_generic_pet_scripts() { + new npc_pet_gen_baby_blizzard_bear(); + new npc_pet_gen_egbert(); + new npc_pet_gen_pandaren_monk(); new npc_pet_gen_mojo(); } diff --git a/src/server/scripts/Pet/pet_script_loader.cpp b/src/server/scripts/Pet/pet_script_loader.cpp new file mode 100644 index 00000000000..c3c0079fd46 --- /dev/null +++ b/src/server/scripts/Pet/pet_script_loader.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_deathknight_pet_scripts(); +void AddSC_generic_pet_scripts(); +void AddSC_hunter_pet_scripts(); +void AddSC_mage_pet_scripts(); +void AddSC_priest_pet_scripts(); +void AddSC_shaman_pet_scripts(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddPetScripts() +{ + AddSC_deathknight_pet_scripts(); + AddSC_generic_pet_scripts(); + AddSC_hunter_pet_scripts(); + AddSC_mage_pet_scripts(); + AddSC_priest_pet_scripts(); + AddSC_shaman_pet_scripts(); +} diff --git a/src/server/scripts/ScriptLoader.cpp.in.cmake b/src/server/scripts/ScriptLoader.cpp.in.cmake new file mode 100644 index 00000000000..33c336a9a93 --- /dev/null +++ b/src/server/scripts/ScriptLoader.cpp.in.cmake @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This file was created automatically from your script configuration! +// Use CMake to reconfigure this file, never change it on your own! + +#cmakedefine TRINITY_IS_DYNAMIC_SCRIPTLOADER + +#include "Define.h" +#include <vector> +#include <string> + +@TRINITY_SCRIPTS_FORWARD_DECL@ +#ifdef TRINITY_IS_DYNAMIC_SCRIPTLOADER +# include "revision_data.h" +# define TC_SCRIPT_API TC_API_EXPORT +extern "C" { + +/// Exposed in script modules to return the script module revision hash. +TC_SCRIPT_API char const* GetScriptModuleRevisionHash() +{ + return _HASH; +} + +/// Exposed in script module to return the name of the script module +/// contained in this shared library. +TC_SCRIPT_API char const* GetScriptModule() +{ + return "@TRINITY_CURRENT_SCRIPT_PROJECT@"; +} + +#else +# include "ScriptLoader.h" +# define TC_SCRIPT_API +#endif + +/// Exposed in script modules to register all scripts to the ScriptMgr. +TC_SCRIPT_API void AddScripts() +{ +@TRINITY_SCRIPTS_INVOKE@} + +/// Exposed in script modules to get the build directive of the module. +TC_SCRIPT_API char const* GetBuildDirective() +{ + return _BUILD_DIRECTIVE; +} + +#ifdef TRINITY_IS_DYNAMIC_SCRIPTLOADER +} // extern "C" +#endif diff --git a/src/server/game/Scripting/ScriptLoader.h b/src/server/scripts/ScriptLoader.h index 4adb215e130..57b62df22d1 100644 --- a/src/server/game/Scripting/ScriptLoader.h +++ b/src/server/scripts/ScriptLoader.h @@ -19,17 +19,5 @@ #define SC_SCRIPTLOADER_H void AddScripts(); -void AddSpellScripts(); -void AddCommandScripts(); -void AddWorldScripts(); -void AddEasternKingdomsScripts(); -void AddKalimdorScripts(); -void AddOutlandScripts(); -void AddNorthrendScripts(); -void AddEventScripts(); -void AddPetScripts(); -void AddBattlegroundScripts(); -void AddOutdoorPvPScripts(); -void AddCustomScripts(); #endif diff --git a/src/server/scripts/PrecompiledHeaders/ScriptPCH.cpp b/src/server/scripts/ScriptPCH.cpp index 41fecf3c60d..41fecf3c60d 100644 --- a/src/server/scripts/PrecompiledHeaders/ScriptPCH.cpp +++ b/src/server/scripts/ScriptPCH.cpp diff --git a/src/server/scripts/PrecompiledHeaders/ScriptPCH.h b/src/server/scripts/ScriptPCH.h index 1cd25309055..1cd25309055 100644 --- a/src/server/scripts/PrecompiledHeaders/ScriptPCH.h +++ b/src/server/scripts/ScriptPCH.h diff --git a/src/server/scripts/Spells/CMakeLists.txt b/src/server/scripts/Spells/CMakeLists.txt deleted file mode 100644 index 7434d98cf49..00000000000 --- a/src/server/scripts/Spells/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - Spells/spell_shaman.cpp - Spells/spell_hunter.cpp - Spells/spell_rogue.cpp - Spells/spell_druid.cpp - Spells/spell_dk.cpp - Spells/spell_quest.cpp - Spells/spell_warrior.cpp - Spells/spell_generic.cpp - Spells/spell_warlock.cpp - Spells/spell_priest.cpp - Spells/spell_mage.cpp - Spells/spell_paladin.cpp - Spells/spell_item.cpp - Spells/spell_holiday.cpp - Spells/spell_pet.cpp -) - -message(" -> Prepared: Spells") diff --git a/src/server/scripts/Spells/spell_dk.cpp b/src/server/scripts/Spells/spell_dk.cpp index 3cea620559a..980c0db19cc 100644 --- a/src/server/scripts/Spells/spell_dk.cpp +++ b/src/server/scripts/Spells/spell_dk.cpp @@ -22,7 +22,7 @@ */ #include "Player.h" -#include "UnitAI.h" +#include "PlayerAI.h" #include "ScriptMgr.h" #include "SpellScript.h" #include "SpellAuraEffects.h" @@ -30,6 +30,13 @@ enum DeathKnightSpells { + SPELL_DK_ACCLIMATION_HOLY = 50490, + SPELL_DK_ACCLIMATION_FIRE = 50362, + SPELL_DK_ACCLIMATION_FROST = 50485, + SPELL_DK_ACCLIMATION_ARCANE = 50486, + SPELL_DK_ACCLIMATION_SHADOW = 50489, + SPELL_DK_ACCLIMATION_NATURE = 50488, + SPELL_DK_ADVANTAGE_T10_4P_MELEE = 70657, SPELL_DK_ANTI_MAGIC_SHELL_TALENT = 51052, SPELL_DK_BLACK_ICE_R1 = 49140, SPELL_DK_BLOOD_BOIL_TRIGGERED = 65658, @@ -51,6 +58,7 @@ enum DeathKnightSpells SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1 = 50365, SPELL_DK_IMPROVED_FROST_PRESENCE_R1 = 50384, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1 = 50391, + SPELL_DK_IMPROVED_BLOOD_PRESENCE_HEAL = 50475, SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED = 63611, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED = 63622, SPELL_DK_ITEM_SIGIL_VENGEFUL_HEART = 64962, @@ -65,8 +73,6 @@ enum DeathKnightSpells SPELL_DK_UNHOLY_PRESENCE_TRIGGERED = 49772, SPELL_DK_WILL_OF_THE_NECROPOLIS_TALENT_R1 = 49189, SPELL_DK_WILL_OF_THE_NECROPOLIS_AURA_R1 = 52284, - SPELL_DK_RAISE_ALLY_INITIAL = 61999, - SPELL_DK_RAISE_ALLY = 46619, SPELL_DK_GHOUL_THRASH = 47480 }; @@ -80,6 +86,141 @@ enum Misc NPC_DK_GHOUL = 26125 }; +// -49200 - Acclimation +class spell_dk_acclimation : public SpellScriptLoader +{ +public: + spell_dk_acclimation() : SpellScriptLoader("spell_dk_acclimation") { } + + class spell_dk_acclimation_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dk_acclimation_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_HOLY) || + !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_FIRE) || + !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_FROST) || + !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_NATURE) || + !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_SHADOW) || + !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_ARCANE)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetDamageInfo()) + { + switch (GetFirstSchoolInMask(eventInfo.GetDamageInfo()->GetSchoolMask())) + { + case SPELL_SCHOOL_HOLY: + case SPELL_SCHOOL_FIRE: + case SPELL_SCHOOL_NATURE: + case SPELL_SCHOOL_FROST: + case SPELL_SCHOOL_SHADOW: + case SPELL_SCHOOL_ARCANE: + return true; + default: + break; + } + } + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + uint32 triggerspell = 0; + + switch (GetFirstSchoolInMask(eventInfo.GetDamageInfo()->GetSchoolMask())) + { + case SPELL_SCHOOL_HOLY: + triggerspell = SPELL_DK_ACCLIMATION_HOLY; + break; + case SPELL_SCHOOL_FIRE: + triggerspell = SPELL_DK_ACCLIMATION_FIRE; + break; + case SPELL_SCHOOL_NATURE: + triggerspell = SPELL_DK_ACCLIMATION_NATURE; + break; + case SPELL_SCHOOL_FROST: + triggerspell = SPELL_DK_ACCLIMATION_FROST; + break; + case SPELL_SCHOOL_SHADOW: + triggerspell = SPELL_DK_ACCLIMATION_SHADOW; + break; + case SPELL_SCHOOL_ARCANE: + triggerspell = SPELL_DK_ACCLIMATION_ARCANE; + break; + default: + return; + } + + if (Unit* target = eventInfo.GetActionTarget()) + target->CastSpell(target, triggerspell, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dk_acclimation_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_dk_acclimation_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dk_acclimation_AuraScript(); + } +}; + +// 70656 - Advantage (T10 4P Melee Bonus) +class spell_dk_advantage_t10_4p : public SpellScriptLoader +{ +public: + spell_dk_advantage_t10_4p() : SpellScriptLoader("spell_dk_advantage_t10_4p") { } + + class spell_dk_advantage_t10_4p_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dk_advantage_t10_4p_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DK_ADVANTAGE_T10_4P_MELEE)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (Unit* caster = eventInfo.GetActor()) + { + if (caster->GetTypeId() != TYPEID_PLAYER || caster->getClass() != CLASS_DEATH_KNIGHT) + return false; + + for (uint8 i = 0; i < MAX_RUNES; ++i) + if (caster->ToPlayer()->GetRuneCooldown(i) == 0) + return false; + + return true; + } + + return false; + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dk_advantage_t10_4p_AuraScript::CheckProc); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dk_advantage_t10_4p_AuraScript(); + } +}; + // 50462 - Anti-Magic Shell (on raid member) class spell_dk_anti_magic_shell_raid : public SpellScriptLoader { @@ -228,7 +369,7 @@ class spell_dk_anti_magic_zone : public SpellScriptLoader void CalculateAmount(AuraEffect const* /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/) { - SpellInfo const* talentSpell = sSpellMgr->EnsureSpellInfo(SPELL_DK_ANTI_MAGIC_SHELL_TALENT); + SpellInfo const* talentSpell = sSpellMgr->AssertSpellInfo(SPELL_DK_ANTI_MAGIC_SHELL_TALENT); amount = talentSpell->Effects[EFFECT_0].CalcValue(GetCaster()); if (Player* player = GetCaster()->ToPlayer()) amount += int32(2 * player->GetTotalAttackPowerValue(BASE_ATTACK)); @@ -921,6 +1062,52 @@ class spell_dk_improved_blood_presence : public SpellScriptLoader } }; +// 63611 - Improved Blood Presence Triggered +class spell_dk_improved_blood_presence_triggered : public SpellScriptLoader +{ +public: + spell_dk_improved_blood_presence_triggered() : SpellScriptLoader("spell_dk_improved_blood_presence_triggered") { } + + class spell_dk_improved_blood_presence_triggered_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dk_improved_blood_presence_triggered_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_HEAL)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetActor()->GetTypeId() == TYPEID_PLAYER) + return true; + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + if (DamageInfo* dmgInfo = eventInfo.GetDamageInfo()) + eventInfo.GetActor()->CastCustomSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_HEAL, SPELLVALUE_BASE_POINT0, CalculatePct(int32(dmgInfo->GetDamage()), aurEff->GetAmount()), + eventInfo.GetActor(), true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dk_improved_blood_presence_triggered_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_dk_improved_blood_presence_triggered_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dk_improved_blood_presence_triggered_AuraScript(); + } +}; + // -50384 - Improved Frost Presence class spell_dk_improved_frost_presence : public SpellScriptLoader { @@ -1636,7 +1823,7 @@ class spell_dk_will_of_the_necropolis : public SpellScriptLoader { // min pct of hp is stored in effect 0 of talent spell uint8 rank = GetSpellInfo()->GetRank(); - SpellInfo const* talentProto = sSpellMgr->EnsureSpellInfo(sSpellMgr->GetSpellWithRank(SPELL_DK_WILL_OF_THE_NECROPOLIS_TALENT_R1, rank)); + SpellInfo const* talentProto = sSpellMgr->AssertSpellInfo(sSpellMgr->GetSpellWithRank(SPELL_DK_WILL_OF_THE_NECROPOLIS_TALENT_R1, rank)); int32 remainingHp = int32(GetTarget()->GetHealth() - dmgInfo.GetDamage()); int32 minHp = int32(GetTarget()->CountPctFromMaxHealth(talentProto->Effects[EFFECT_0].CalcValue(GetCaster()))); @@ -1733,36 +1920,39 @@ public: { PrepareSpellScript(spell_dk_raise_ally_initial_SpellScript); - bool Validate(SpellInfo const* /*spellInfo*/) override + bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RAISE_ALLY_INITIAL)) + if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_0].CalcValue()))) return false; return true; } + bool Load() override + { + return GetCaster()->GetTypeId() == TYPEID_PLAYER; + } + SpellCastResult CheckCast() { - // Raise Ally cannot be casted on alive players Unit* target = GetExplTargetUnit(); if (!target) return SPELL_FAILED_NO_VALID_TARGETS; if (target->IsAlive()) return SPELL_FAILED_TARGET_NOT_DEAD; - if (Player* playerCaster = GetCaster()->ToPlayer()) - if (playerCaster->InArena()) - return SPELL_FAILED_NOT_IN_ARENA; if (target->IsGhouled()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; - return SPELL_CAST_OK; } void HandleDummy(SpellEffIndex /*effIndex*/) { - Player* caster = GetCaster()->ToPlayer(); - Player* target = GetHitPlayer(); - if (caster && target) - caster->SendGhoulResurrectRequest(target); + if (Player* target = GetHitPlayer()) + { + if (target->IsResurrectRequested()) // already have one active request + return; + target->SetResurrectRequestData(GetCaster(), 0, 0, uint32(GetEffectValue())); + GetSpell()->SendResurrectRequest(target); + } } void Register() override @@ -1785,12 +1975,8 @@ class player_ghoulAI : public PlayerAI void UpdateAI(uint32 /*diff*/) override { - if (Creature* ghoul = ObjectAccessor::GetCreature(*me, _ghoulGUID)) - { - if (!ghoul->IsAlive()) - me->RemoveAura(SPELL_DK_RAISE_ALLY); - } - else + Creature* ghoul = ObjectAccessor::GetCreature(*me, _ghoulGUID); + if (!ghoul || !ghoul->IsAlive()) me->RemoveAura(SPELL_DK_RAISE_ALLY); } @@ -1799,28 +1985,25 @@ class player_ghoulAI : public PlayerAI }; // 46619 - Raise Ally +#define DkRaiseAllyScriptName "spell_dk_raise_ally" class spell_dk_raise_ally : public SpellScriptLoader { public: - spell_dk_raise_ally() : SpellScriptLoader("spell_dk_raise_ally") { } + spell_dk_raise_ally() : SpellScriptLoader(DkRaiseAllyScriptName) { } class spell_dk_raise_ally_SpellScript : public SpellScript { PrepareSpellScript(spell_dk_raise_ally_SpellScript); - bool Validate(SpellInfo const* /*spellInfo*/) override + bool Load() override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RAISE_ALLY)) - return false; - return true; + return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void SendText() { - Player* caster = GetCaster()->ToPlayer(); - Unit* original = GetOriginalCaster(); - if (caster && original) - original->Whisper(TEXT_RISE_ALLY, caster, true); + if (Unit* original = GetOriginalCaster()) + original->Whisper(TEXT_RISE_ALLY, GetCaster()->ToPlayer(), true); } void HandleSummon(SpellEffIndex effIndex) @@ -1839,9 +2022,8 @@ public: SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(829); uint32 duration = uint32(GetSpellInfo()->GetDuration()); - Position pos = caster->GetPosition(); - TempSummon* summon = originalCaster->GetMap()->SummonCreature(entry, pos, properties, duration, originalCaster, GetSpellInfo()->Id); + TempSummon* summon = originalCaster->GetMap()->SummonCreature(entry, *GetHitDest(), properties, duration, originalCaster, GetSpellInfo()->Id); if (!summon) return; @@ -1868,15 +2050,25 @@ public: // SMSG_POWER_UPDATE is sent summon->SetMaxPower(POWER_ENERGY, 100); - if (Player* player = GetCaster()->ToPlayer()) - player->SetGhoulResurrectGhoulGUID(summon->GetGUID()); + _ghoulGuid = summon->GetGUID(); + } + + void SetGhoul(SpellEffIndex /*effIndex*/) + { + if (Aura* aura = GetHitAura()) + if (spell_dk_raise_ally_AuraScript* script = dynamic_cast<spell_dk_raise_ally_AuraScript*>(aura->GetScriptByName(DkRaiseAllyScriptName))) + script->SetGhoulGuid(_ghoulGuid); } void Register() override { AfterHit += SpellHitFn(spell_dk_raise_ally_SpellScript::SendText); OnEffectHit += SpellEffectFn(spell_dk_raise_ally_SpellScript::HandleSummon, EFFECT_0, SPELL_EFFECT_SUMMON); + OnEffectHitTarget += SpellEffectFn(spell_dk_raise_ally_SpellScript::SetGhoul, EFFECT_1, SPELL_EFFECT_APPLY_AURA); } + + private: + ObjectGuid _ghoulGuid; }; SpellScript* GetSpellScript() const override @@ -1895,45 +2087,45 @@ public: oldAIState = false; } + void SetGhoulGuid(ObjectGuid guid) + { + ghoulGuid = guid; + } + private: - bool Validate(SpellInfo const* /*spellInfo*/) override + bool Load() override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RAISE_ALLY)) - return false; - return true; + return GetUnitOwner()->GetTypeId() == TYPEID_PLAYER; } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Player* player = GetTarget()->ToPlayer(); - if (!player || player->GetGhoulResurrectGhoulGUID().IsEmpty()) + if (ghoulGuid.IsEmpty()) return; - oldAI = player->GetAI(); + oldAI = player->AI(); oldAIState = player->IsAIEnabled; - player->SetAI(new player_ghoulAI(player, player->GetGhoulResurrectGhoulGUID())); + player->SetAI(new player_ghoulAI(player, ghoulGuid)); player->IsAIEnabled = true; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Player* player = GetTarget()->ToPlayer(); - if (!player) - return; player->IsAIEnabled = oldAIState; - UnitAI* thisAI = player->GetAI(); + PlayerAI* thisAI = player->AI(); player->SetAI(oldAI); delete thisAI; // Dismiss ghoul if necessary - if (Creature* ghoul = ObjectAccessor::GetCreature(*player, player->GetGhoulResurrectGhoulGUID())) + if (Creature* ghoul = ObjectAccessor::GetCreature(*player, ghoulGuid)) { - ghoul->RemoveCharmedBy(nullptr); + ghoul->RemoveCharmedBy(player); ghoul->DespawnOrUnsummon(1000); } - player->SetGhoulResurrectGhoulGUID(ObjectGuid::Empty); player->RemoveAura(SPELL_GHOUL_FRENZY); } @@ -1943,7 +2135,8 @@ public: AfterEffectRemove += AuraEffectRemoveFn(spell_dk_raise_ally_AuraScript::OnRemove, EFFECT_1, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } - UnitAI* oldAI; + ObjectGuid ghoulGuid; + PlayerAI* oldAI; bool oldAIState; }; @@ -1965,7 +2158,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_GHOUL_THRASH)) + if (!sSpellMgr->GetSpellInfo(SPELL_GHOUL_FRENZY)) return false; return true; } @@ -2002,6 +2195,8 @@ public: void AddSC_deathknight_spell_scripts() { + new spell_dk_acclimation(); + new spell_dk_advantage_t10_4p(); new spell_dk_anti_magic_shell_raid(); new spell_dk_anti_magic_shell_self(); new spell_dk_anti_magic_zone(); @@ -2018,6 +2213,7 @@ void AddSC_deathknight_spell_scripts() new spell_dk_ghoul_explode(); new spell_dk_icebound_fortitude(); new spell_dk_improved_blood_presence(); + new spell_dk_improved_blood_presence_triggered(); new spell_dk_improved_frost_presence(); new spell_dk_improved_unholy_presence(); new spell_dk_pestilence(); diff --git a/src/server/scripts/Spells/spell_druid.cpp b/src/server/scripts/Spells/spell_druid.cpp index 7b853c36075..0bf5ab01f45 100644 --- a/src/server/scripts/Spells/spell_druid.cpp +++ b/src/server/scripts/Spells/spell_druid.cpp @@ -31,6 +31,13 @@ enum DruidSpells { SPELL_DRUID_BEAR_FORM_PASSIVE = 1178, SPELL_DRUID_DIRE_BEAR_FORM_PASSIVE = 9635, + SPELL_DRUID_ECLIPSE_LUNAR_PROC = 48518, + SPELL_DRUID_ECLIPSE_SOLAR_PROC = 48517, + SPELL_DRUID_FORMS_TRINKET_BEAR = 37340, + SPELL_DRUID_FORMS_TRINKET_CAT = 37341, + SPELL_DRUID_FORMS_TRINKET_MOONKIN = 37343, + SPELL_DRUID_FORMS_TRINKET_NONE = 37344, + SPELL_DRUID_FORMS_TRINKET_TREE = 37342, SPELL_DRUID_ENRAGE = 5229, SPELL_DRUID_ENRAGE_MOD_DAMAGE = 51185, SPELL_DRUID_ENRAGED_DEFENSE = 70725, @@ -48,6 +55,8 @@ enum DruidSpells SPELL_DRUID_NATURES_SPLENDOR = 57865, SPELL_DRUID_SURVIVAL_INSTINCTS = 50322, SPELL_DRUID_SAVAGE_ROAR = 62071, + SPELL_DRUID_T9_FERAL_RELIC_BEAR = 67354, + SPELL_DRUID_T9_FERAL_RELIC_CAT = 67355, SPELL_DRUID_TIGER_S_FURY_ENERGIZE = 51178 }; @@ -131,6 +140,69 @@ class spell_dru_dash : public SpellScriptLoader } }; +class spell_dru_eclipse : public SpellScriptLoader +{ +public: + spell_dru_eclipse() : SpellScriptLoader("spell_dru_eclipse") { } + + class spell_dru_eclipse_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dru_eclipse_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_ECLIPSE_LUNAR_PROC)) + return false; + if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_ECLIPSE_SOLAR_PROC)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (!eventInfo.GetSpellInfo()) + return false; + + if (eventInfo.GetActor()->HasAura(SPELL_DRUID_ECLIPSE_LUNAR_PROC) || eventInfo.GetActor()->HasAura(SPELL_DRUID_ECLIPSE_SOLAR_PROC)) + return false; + + // Triggered by Wrath? + if (eventInfo.GetSpellInfo()->SpellFamilyFlags[0] & 1) + return roll_chance_f(GetSpellInfo()->ProcChance * 0.6f) && _lunarProcCooldownEnd <= std::chrono::steady_clock::now(); + + return _solarProcCooldownEnd <= std::chrono::steady_clock::now(); + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + if (eventInfo.GetSpellInfo()->SpellFamilyFlags[0] & 1) + { + _lunarProcCooldownEnd = std::chrono::steady_clock::now() + Seconds(aurEff->GetAmount()); + eventInfo.GetActor()->CastSpell(eventInfo.GetActor(), SPELL_DRUID_ECLIPSE_LUNAR_PROC, TRIGGERED_FULL_MASK, nullptr, aurEff); + } + else + { + _solarProcCooldownEnd = std::chrono::steady_clock::now() + Seconds(aurEff->GetAmount()); + eventInfo.GetActor()->CastSpell(eventInfo.GetActor(), SPELL_DRUID_ECLIPSE_SOLAR_PROC, TRIGGERED_FULL_MASK, nullptr, aurEff); + } + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dru_eclipse_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_dru_eclipse_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); + } + + std::chrono::steady_clock::time_point _lunarProcCooldownEnd = std::chrono::steady_clock::time_point::min(); + std::chrono::steady_clock::time_point _solarProcCooldownEnd = std::chrono::steady_clock::time_point::min(); + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dru_eclipse_AuraScript(); + } +}; + // 5229 - Enrage class spell_dru_enrage : public SpellScriptLoader { @@ -197,6 +269,91 @@ class spell_dru_enrage : public SpellScriptLoader } }; +// 37336 - Druid Forms Trinket +class spell_dru_forms_trinket : public SpellScriptLoader +{ +public: + spell_dru_forms_trinket() : SpellScriptLoader("spell_dru_forms_trinket") { } + + class spell_dru_forms_trinket_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dru_forms_trinket_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_BEAR) || + !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_CAT) || + !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_MOONKIN) || + !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_NONE) || + !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_TREE)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + Unit* target = eventInfo.GetActor(); + + switch (target->GetShapeshiftForm()) + { + case FORM_BEAR: + case FORM_DIREBEAR: + case FORM_CAT: + case FORM_MOONKIN: + case FORM_NONE: + case FORM_TREE: + return true; + default: + break; + } + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + Unit* target = eventInfo.GetActor(); + uint32 triggerspell = 0; + + switch (target->GetShapeshiftForm()) + { + case FORM_BEAR: + case FORM_DIREBEAR: + triggerspell = SPELL_DRUID_FORMS_TRINKET_BEAR; + break; + case FORM_CAT: + triggerspell = SPELL_DRUID_FORMS_TRINKET_CAT; + break; + case FORM_MOONKIN: + triggerspell = SPELL_DRUID_FORMS_TRINKET_MOONKIN; + break; + case FORM_NONE: + triggerspell = SPELL_DRUID_FORMS_TRINKET_NONE; + break; + case FORM_TREE: + triggerspell = SPELL_DRUID_FORMS_TRINKET_TREE; + break; + default: + return; + } + + target->CastSpell(target, triggerspell, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dru_forms_trinket_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_dru_forms_trinket_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dru_forms_trinket_AuraScript(); + } +}; + // 54846 - Glyph of Starfire class spell_dru_glyph_of_starfire : public SpellScriptLoader { @@ -991,6 +1148,37 @@ class spell_dru_swift_flight_passive : public SpellScriptLoader } }; +// -33943 - Flight Form +class spell_dru_flight_form : public SpellScriptLoader +{ + public: + spell_dru_flight_form() : SpellScriptLoader("spell_dru_flight_form") { } + + class spell_dru_flight_form_SpellScript : public SpellScript + { + PrepareSpellScript(spell_dru_flight_form_SpellScript); + + SpellCastResult CheckCast() + { + Unit* caster = GetCaster(); + if (caster->IsInDisallowedMountForm()) + return SPELL_FAILED_NOT_SHAPESHIFT; + + return SPELL_CAST_OK; + } + + void Register() override + { + OnCheckCast += SpellCheckCastFn(spell_dru_flight_form_SpellScript::CheckCast); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_dru_flight_form_SpellScript(); + } +}; + // -5217 - Tiger's Fury class spell_dru_tiger_s_fury : public SpellScriptLoader { @@ -1048,6 +1236,77 @@ class spell_dru_typhoon : public SpellScriptLoader } }; +// 67353 - T9 Feral Relic (Idol of Mutilation) +class spell_dru_t9_feral_relic : public SpellScriptLoader +{ +public: + spell_dru_t9_feral_relic() : SpellScriptLoader("spell_dru_t9_feral_relic") { } + + class spell_dru_t9_feral_relic_AuraScript : public AuraScript + { + PrepareAuraScript(spell_dru_t9_feral_relic_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_T9_FERAL_RELIC_BEAR) || + !sSpellMgr->GetSpellInfo(SPELL_DRUID_T9_FERAL_RELIC_CAT)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + Unit* target = eventInfo.GetActor(); + + switch (target->GetShapeshiftForm()) + { + case FORM_BEAR: + case FORM_DIREBEAR: + case FORM_CAT: + return true; + default: + break; + } + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + uint32 triggerspell = 0; + + Unit* target = eventInfo.GetActor(); + + switch (target->GetShapeshiftForm()) + { + case FORM_BEAR: + case FORM_DIREBEAR: + triggerspell = SPELL_DRUID_T9_FERAL_RELIC_BEAR; + break; + case FORM_CAT: + triggerspell = SPELL_DRUID_T9_FERAL_RELIC_CAT; + break; + default: + return; + } + + target->CastSpell(target, triggerspell, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_dru_t9_feral_relic_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_dru_t9_feral_relic_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_dru_t9_feral_relic_AuraScript(); + } +}; + // 70691 - Item T10 Restoration 4P Bonus class spell_dru_t10_restoration_4p_bonus : public SpellScriptLoader { @@ -1177,7 +1436,9 @@ void AddSC_druid_spell_scripts() { new spell_dru_bear_form_passive(); new spell_dru_dash(); + new spell_dru_eclipse(); new spell_dru_enrage(); + new spell_dru_forms_trinket(); new spell_dru_glyph_of_starfire(); new spell_dru_idol_lifebloom(); new spell_dru_innervate(); @@ -1196,8 +1457,10 @@ void AddSC_druid_spell_scripts() new spell_dru_starfall_dummy(); new spell_dru_survival_instincts(); new spell_dru_swift_flight_passive(); + new spell_dru_flight_form(); new spell_dru_tiger_s_fury(); new spell_dru_typhoon(); + new spell_dru_t9_feral_relic(); new spell_dru_t10_restoration_4p_bonus(); new spell_dru_wild_growth(); } diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index abde43ef952..e8ad73ceadb 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -430,6 +430,61 @@ class spell_gen_bandage : public SpellScriptLoader } }; +// Blood Reserve - 64568 +enum BloodReserve +{ + SPELL_GEN_BLOOD_RESERVE_AURA = 64568, + SPELL_GEN_BLOOD_RESERVE_HEAL = 64569 +}; + +class spell_gen_blood_reserve : public SpellScriptLoader +{ + public: + spell_gen_blood_reserve() : SpellScriptLoader("spell_gen_blood_reserve") { } + + class spell_gen_blood_reserve_AuraScript : public AuraScript + { + PrepareAuraScript(spell_gen_blood_reserve_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_GEN_BLOOD_RESERVE_HEAL)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (DamageInfo* dmgInfo = eventInfo.GetDamageInfo()) + if (Unit* caster = eventInfo.GetActionTarget()) + if (caster->HealthBelowPctDamaged(35, dmgInfo->GetDamage())) + return true; + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActionTarget(); + caster->CastCustomSpell(SPELL_GEN_BLOOD_RESERVE_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), caster, TRIGGERED_FULL_MASK, nullptr, aurEff); + caster->RemoveAura(SPELL_GEN_BLOOD_RESERVE_AURA); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_gen_blood_reserve_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_gen_blood_reserve_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_gen_blood_reserve_AuraScript(); + } +}; + enum Bonked { SPELL_BONKED = 62991, @@ -1245,7 +1300,7 @@ class spell_gen_defend : public SpellScriptLoader void Register() override { - SpellInfo const* spell = sSpellMgr->EnsureSpellInfo(m_scriptSpellId); + SpellInfo const* spell = sSpellMgr->AssertSpellInfo(m_scriptSpellId); // Defend spells cast by NPCs (add visuals) if (spell->Effects[EFFECT_0].ApplyAuraName == SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN) @@ -2085,7 +2140,7 @@ class spell_gen_mounted_charge: public SpellScriptLoader } // If target isn't a training dummy there's a chance of failing the charge - if (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE) && roll_chance_f(12.5f)) + if (!target->IsCharmedOwnedByPlayerOrPlayer() && roll_chance_f(12.5f)) spellId = SPELL_CHARGE_MISS_EFFECT; if (Unit* vehicle = GetCaster()->GetVehicleBase()) @@ -2148,7 +2203,7 @@ class spell_gen_mounted_charge: public SpellScriptLoader void Register() override { - SpellInfo const* spell = sSpellMgr->EnsureSpellInfo(m_scriptSpellId); + SpellInfo const* spell = sSpellMgr->AssertSpellInfo(m_scriptSpellId); if (spell->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT)) OnEffectHitTarget += SpellEffectFn(spell_gen_mounted_charge_SpellScript::HandleScriptEffect, EFFECT_FIRST_FOUND, SPELL_EFFECT_SCRIPT_EFFECT); @@ -4155,6 +4210,40 @@ public: } }; +// 34098 - ClearAllDebuffs +class spell_gen_clear_debuffs : public SpellScriptLoader +{ + public: + spell_gen_clear_debuffs() : SpellScriptLoader("spell_gen_clear_debuffs") { } + + class spell_gen_clear_debuffs_SpellScript : public SpellScript + { + PrepareSpellScript(spell_gen_clear_debuffs_SpellScript); + + void HandleScript(SpellEffIndex /*effIndex*/) + { + if (Unit* target = GetHitUnit()) + { + target->RemoveOwnedAuras([](Aura const* aura) + { + SpellInfo const* spellInfo = aura->GetSpellInfo(); + return !spellInfo->IsPositive() && !spellInfo->IsPassive(); + }); + } + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_gen_clear_debuffs_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_gen_clear_debuffs_SpellScript(); + } +}; + void AddSC_generic_spell_scripts() { new spell_gen_absorb0_hitlimit1(); @@ -4165,6 +4254,7 @@ void AddSC_generic_spell_scripts() new spell_gen_aura_service_uniform(); new spell_gen_av_drekthar_presence(); new spell_gen_bandage(); + new spell_gen_blood_reserve(); new spell_gen_bonked(); new spell_gen_break_shield("spell_gen_break_shield"); new spell_gen_break_shield("spell_gen_tournament_counterattack"); @@ -4241,4 +4331,5 @@ void AddSC_generic_spell_scripts() new spell_gen_stand(); new spell_gen_mixology_bonus(); new spell_gen_landmine_knockback_achievement(); + new spell_gen_clear_debuffs(); } diff --git a/src/server/scripts/Spells/spell_holiday.cpp b/src/server/scripts/Spells/spell_holiday.cpp index 7fe1f54a594..bd36e3cb765 100644 --- a/src/server/scripts/Spells/spell_holiday.cpp +++ b/src/server/scripts/Spells/spell_holiday.cpp @@ -29,6 +29,7 @@ #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" +#include "Vehicle.h" // 45102 Romantic Picnic enum SpellsPicnic @@ -64,7 +65,7 @@ class spell_love_is_in_the_air_romantic_picnic : public SpellScriptLoader Unit* caster = GetCaster(); // If our player is no longer sit, remove all auras - if (target->getStandState() != UNIT_STAND_STATE_SIT) + if (target->GetStandState() != UNIT_STAND_STATE_SIT) { target->RemoveAura(SPELL_ROMANTIC_PICNIC_ACHIEV); target->RemoveAura(GetAura()); @@ -83,7 +84,7 @@ class spell_love_is_in_the_air_romantic_picnic : public SpellScriptLoader target->VisitNearbyWorldObject(INTERACTION_DISTANCE*2, searcher); for (std::list<Player*>::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) { - if ((*itr) != target && (*itr)->HasAura(GetId())) // && (*itr)->getStandState() == UNIT_STAND_STATE_SIT) + if ((*itr) != target && (*itr)->HasAura(GetId())) // && (*itr)->GetStandState() == UNIT_STAND_STATE_SIT) { if (caster) { @@ -112,6 +113,105 @@ class spell_love_is_in_the_air_romantic_picnic : public SpellScriptLoader } }; +enum HallowEndCandysSpells +{ + SPELL_HALLOWS_END_CANDY_ORANGE_GIANT = 24924, // Effect 1: Apply Aura: Mod Size, Value: 30% + SPELL_HALLOWS_END_CANDY_SKELETON = 24925, // Effect 1: Apply Aura: Change Model (Skeleton). Effect 2: Apply Aura: Underwater Breathing + SPELL_HALLOWS_END_CANDY_PIRATE = 24926, // Effect 1: Apply Aura: Increase Swim Speed, Value: 50% + SPELL_HALLOWS_END_CANDY_GHOST = 24927, // Effect 1: Apply Aura: Levitate / Hover. Effect 2: Apply Aura: Slow Fall, Effect 3: Apply Aura: Water Walking + SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE = 44742, // Effect 1: Apply Aura: Change Model (Defias Pirate, Female). Effect 2: Increase Swim Speed, Value: 50% + SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE = 44743 // Effect 1: Apply Aura: Change Model (Defias Pirate, Male). Effect 2: Increase Swim Speed, Value: 50% +}; + +// 24930 - Hallow's End Candy +class spell_hallow_end_candy : public SpellScriptLoader +{ + public: + spell_hallow_end_candy() : SpellScriptLoader("spell_hallow_end_candy") { } + + class spell_hallow_end_candy_SpellScript : public SpellScript + { + PrepareSpellScript(spell_hallow_end_candy_SpellScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + for (uint32 spellId : spells) + if (!sSpellMgr->GetSpellInfo(spellId)) + return false; + return true; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + GetCaster()->CastSpell(GetCaster(), spells[urand(0, 3)], true); + } + + void Register() override + { + OnEffectHit += SpellEffectFn(spell_hallow_end_candy_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + + private: + static uint32 const spells[4]; + }; + + SpellScript* GetSpellScript() const override + { + return new spell_hallow_end_candy_SpellScript(); + } +}; + +uint32 const spell_hallow_end_candy::spell_hallow_end_candy_SpellScript::spells[4] = +{ + SPELL_HALLOWS_END_CANDY_ORANGE_GIANT, + SPELL_HALLOWS_END_CANDY_SKELETON, + SPELL_HALLOWS_END_CANDY_PIRATE, + SPELL_HALLOWS_END_CANDY_GHOST +}; + +// 24926 - Hallow's End Candy +class spell_hallow_end_candy_pirate : public SpellScriptLoader +{ + public: + spell_hallow_end_candy_pirate() : SpellScriptLoader("spell_hallow_end_candy_pirate") { } + + class spell_hallow_end_candy_pirate_AuraScript : public AuraScript + { + PrepareAuraScript(spell_hallow_end_candy_pirate_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE) + || !sSpellMgr->GetSpellInfo(SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE)) + return false; + return true; + } + + void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + uint32 spell = GetTarget()->getGender() == GENDER_FEMALE ? SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE : SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE; + GetTarget()->CastSpell(GetTarget(), spell, true); + } + + void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + uint32 spell = GetTarget()->getGender() == GENDER_FEMALE ? SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE : SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE; + GetTarget()->RemoveAurasDueToSpell(spell); + } + + void Register() override + { + AfterEffectApply += AuraEffectApplyFn(spell_hallow_end_candy_pirate_AuraScript::HandleApply, EFFECT_0, SPELL_AURA_MOD_INCREASE_SWIM_SPEED, AURA_EFFECT_HANDLE_REAL); + AfterEffectRemove += AuraEffectRemoveFn(spell_hallow_end_candy_pirate_AuraScript::HandleRemove, EFFECT_0, SPELL_AURA_MOD_INCREASE_SWIM_SPEED, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_hallow_end_candy_pirate_AuraScript(); + } +}; + // 24750 Trick enum TrickSpells { @@ -410,6 +510,84 @@ class spell_pilgrims_bounty_buff_food : public SpellScriptLoader } }; +enum FeastOnSpells +{ + FEAST_ON_TURKEY = 61784, + FEAST_ON_CRANBERRIES = 61785, + FEAST_ON_SWEET_POTATOES = 61786, + FEAST_ON_PIE = 61787, + FEAST_ON_STUFFING = 61788, + SPELL_CRANBERRY_HELPINS = 61841, + SPELL_TURKEY_HELPINS = 61842, + SPELL_STUFFING_HELPINS = 61843, + SPELL_SWEET_POTATO_HELPINS = 61844, + SPELL_PIE_HELPINS = 61845, + SPELL_ON_PLATE_EAT_VISUAL = 61826 +}; + +class spell_pilgrims_bounty_feast_on : public SpellScriptLoader +{ + public: + spell_pilgrims_bounty_feast_on() : SpellScriptLoader("spell_pilgrims_bounty_feast_on") { } + + class spell_pilgrims_bounty_feast_on_SpellScript : public SpellScript + { + PrepareSpellScript(spell_pilgrims_bounty_feast_on_SpellScript); + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + Unit* caster = GetCaster(); + + uint32 _spellId = 0; + switch (GetSpellInfo()->Id) + { + case FEAST_ON_TURKEY: + _spellId = SPELL_TURKEY_HELPINS; + break; + case FEAST_ON_CRANBERRIES: + _spellId = SPELL_CRANBERRY_HELPINS; + break; + case FEAST_ON_SWEET_POTATOES: + _spellId = SPELL_SWEET_POTATO_HELPINS; + break; + case FEAST_ON_PIE: + _spellId = SPELL_PIE_HELPINS; + break; + case FEAST_ON_STUFFING: + _spellId = SPELL_STUFFING_HELPINS; + break; + default: + return; + } + + if (Vehicle* vehicle = caster->GetVehicleKit()) + if (Unit* target = vehicle->GetPassenger(0)) + if (Player* player = target->ToPlayer()) + { + player->CastSpell(player, SPELL_ON_PLATE_EAT_VISUAL, true); + caster->CastSpell(player, _spellId, true, NULL, NULL, player->GetGUID()); + } + + if (Aura* aura = caster->GetAura(GetEffectValue())) + { + if (aura->GetStackAmount() == 1) + caster->RemoveAurasDueToSpell(aura->GetSpellInfo()->Effects[EFFECT_0].CalcValue()); + aura->ModStackAmount(-1); + } + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_feast_on_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_pilgrims_bounty_feast_on_SpellScript(); + } +}; + enum TheTurkinator { SPELL_KILL_COUNTER_VISUAL = 62015, @@ -429,7 +607,7 @@ class spell_pilgrims_bounty_turkey_tracker : public SpellScriptLoader { PrepareSpellScript(spell_pilgrims_bounty_turkey_tracker_SpellScript); - bool Validate(SpellInfo const* /*spell*/) + bool Validate(SpellInfo const* /*spell*/) override { if (!sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL_MAX)) return false; @@ -472,18 +650,90 @@ class spell_pilgrims_bounty_turkey_tracker : public SpellScriptLoader } } - void Register() + void Register() override { OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_turkey_tracker_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); } }; - SpellScript* GetSpellScript() const + SpellScript* GetSpellScript() const override { return new spell_pilgrims_bounty_turkey_tracker_SpellScript(); } }; +enum SpiritOfSharing +{ + SPELL_THE_SPIRIT_OF_SHARING = 61849 +}; + +class spell_pilgrims_bounty_well_fed : public SpellScriptLoader +{ + private: + uint32 _triggeredSpellId; + + public: + spell_pilgrims_bounty_well_fed(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + + class spell_pilgrims_bounty_well_fed_SpellScript : public SpellScript + { + PrepareSpellScript(spell_pilgrims_bounty_well_fed_SpellScript); + private: + uint32 _triggeredSpellId; + + public: + spell_pilgrims_bounty_well_fed_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } + + bool Validate(SpellInfo const* /*spell*/) override + { + if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) + return false; + return true; + } + + void HandleScript(SpellEffIndex effIndex) + { + PreventHitDefaultEffect(effIndex); + Player* target = GetHitPlayer(); + if (!target) + return; + + if (Aura const* aura = target->GetAura(GetSpellInfo()->Id)) + { + if (aura->GetStackAmount() == 5) + target->CastSpell(target, _triggeredSpellId, true); + } + + Aura const* turkey = target->GetAura(SPELL_TURKEY_HELPINS); + Aura const* cranberies = target->GetAura(SPELL_CRANBERRY_HELPINS); + Aura const* stuffing = target->GetAura(SPELL_STUFFING_HELPINS); + Aura const* sweetPotatoes = target->GetAura(SPELL_SWEET_POTATO_HELPINS); + Aura const* pie = target->GetAura(SPELL_PIE_HELPINS); + + if ((turkey && turkey->GetStackAmount() == 5) && (cranberies && cranberies->GetStackAmount() == 5) && (stuffing && stuffing->GetStackAmount() == 5) + && (sweetPotatoes && sweetPotatoes->GetStackAmount() == 5) && (pie && pie->GetStackAmount() == 5)) + { + target->CastSpell(target, SPELL_THE_SPIRIT_OF_SHARING, true); + target->RemoveAurasDueToSpell(SPELL_TURKEY_HELPINS); + target->RemoveAurasDueToSpell(SPELL_CRANBERRY_HELPINS); + target->RemoveAurasDueToSpell(SPELL_STUFFING_HELPINS); + target->RemoveAurasDueToSpell(SPELL_SWEET_POTATO_HELPINS); + target->RemoveAurasDueToSpell(SPELL_PIE_HELPINS); + } + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_well_fed_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_pilgrims_bounty_well_fed_SpellScript(_triggeredSpellId); + } +}; + enum Mistletoe { SPELL_CREATE_MISTLETOE = 26206, @@ -1032,11 +1282,79 @@ class spell_midsummer_braziers_hit : public SpellScriptLoader } }; +enum RibbonPoleData +{ + SPELL_HAS_FULL_MIDSUMMER_SET = 58933, + SPELL_BURNING_HOT_POLE_DANCE = 58934, + SPELL_RIBBON_DANCE_COSMETIC = 29726, + SPELL_RIBBON_DANCE = 29175, + GO_RIBBON_POLE = 181605, +}; + +class spell_gen_ribbon_pole_dancer_check : public SpellScriptLoader +{ + public: + spell_gen_ribbon_pole_dancer_check() : SpellScriptLoader("spell_gen_ribbon_pole_dancer_check") { } + + class spell_gen_ribbon_pole_dancer_check_AuraScript : public AuraScript + { + PrepareAuraScript(spell_gen_ribbon_pole_dancer_check_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_HAS_FULL_MIDSUMMER_SET) + || !sSpellMgr->GetSpellInfo(SPELL_RIBBON_DANCE) + || !sSpellMgr->GetSpellInfo(SPELL_BURNING_HOT_POLE_DANCE)) + return false; + return true; + } + + void PeriodicTick(AuraEffect const* /*aurEff*/) + { + Unit* target = GetTarget(); + + // check if aura needs to be removed + if (!target->FindNearestGameObject(GO_RIBBON_POLE, 8.0f) || !target->HasUnitState(UNIT_STATE_CASTING)) + { + target->InterruptNonMeleeSpells(false); + target->RemoveAurasDueToSpell(GetId()); + target->RemoveAura(SPELL_RIBBON_DANCE_COSMETIC); + return; + } + + // set xp buff duration + if (Aura* aur = target->GetAura(SPELL_RIBBON_DANCE)) + { + aur->SetMaxDuration(std::min(3600000, aur->GetMaxDuration() + 180000)); + aur->RefreshDuration(); + + // reward achievement criteria + if (aur->GetMaxDuration() == 3600000 && target->HasAura(SPELL_HAS_FULL_MIDSUMMER_SET)) + target->CastSpell(target, SPELL_BURNING_HOT_POLE_DANCE, true); + } + else + target->AddAura(SPELL_RIBBON_DANCE, target); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(spell_gen_ribbon_pole_dancer_check_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_gen_ribbon_pole_dancer_check_AuraScript(); + } +}; + void AddSC_holiday_spell_scripts() { // Love is in the Air new spell_love_is_in_the_air_romantic_picnic(); // Hallow's End + new spell_hallow_end_candy(); + new spell_hallow_end_candy_pirate(); new spell_hallow_end_trick(); new spell_hallow_end_trick_or_treat(); new spell_hallow_end_tricky_treat(); @@ -1047,6 +1365,12 @@ void AddSC_holiday_spell_scripts() new spell_pilgrims_bounty_buff_food("spell_gen_spice_bread_stuffing", SPELL_WELL_FED_HIT_TRIGGER); new spell_pilgrims_bounty_buff_food("spell_gen_pumpkin_pie", SPELL_WELL_FED_SPIRIT_TRIGGER); new spell_pilgrims_bounty_buff_food("spell_gen_candied_sweet_potato", SPELL_WELL_FED_HASTE_TRIGGER); + new spell_pilgrims_bounty_feast_on(); + new spell_pilgrims_bounty_well_fed("spell_pilgrims_bounty_well_fed_turkey", SPELL_WELL_FED_AP_TRIGGER); + new spell_pilgrims_bounty_well_fed("spell_pilgrims_bounty_well_fed_cranberry", SPELL_WELL_FED_ZM_TRIGGER); + new spell_pilgrims_bounty_well_fed("spell_pilgrims_bounty_well_fed_stuffing", SPELL_WELL_FED_HIT_TRIGGER); + new spell_pilgrims_bounty_well_fed("spell_pilgrims_bounty_well_fed_sweet_potatoes", SPELL_WELL_FED_HASTE_TRIGGER); + new spell_pilgrims_bounty_well_fed("spell_pilgrims_bounty_well_fed_pie", SPELL_WELL_FED_SPIRIT_TRIGGER); new spell_pilgrims_bounty_turkey_tracker(); // Winter Veil new spell_winter_veil_mistletoe(); @@ -1062,4 +1386,5 @@ void AddSC_holiday_spell_scripts() new spell_brewfest_barker_bunny(); // Midsummer Fire Festival new spell_midsummer_braziers_hit(); + new spell_gen_ribbon_pole_dancer_check(); } diff --git a/src/server/scripts/Spells/spell_hunter.cpp b/src/server/scripts/Spells/spell_hunter.cpp index abf4c6c1ad8..a75294ad6e0 100644 --- a/src/server/scripts/Spells/spell_hunter.cpp +++ b/src/server/scripts/Spells/spell_hunter.cpp @@ -40,6 +40,7 @@ enum HunterSpells SPELL_HUNTER_CHIMERA_SHOT_SERPENT = 53353, SPELL_HUNTER_CHIMERA_SHOT_VIPER = 53358, SPELL_HUNTER_CHIMERA_SHOT_SCORPID = 53359, + SPELL_HUNTER_GLYPH_OF_ARCANE_SHOT = 61389, SPELL_HUNTER_GLYPH_OF_ASPECT_OF_THE_VIPER = 56851, SPELL_HUNTER_IMPROVED_MEND_PET = 24406, SPELL_HUNTER_INVIGORATION_TRIGGERED = 53398, @@ -50,12 +51,15 @@ enum HunterSpells SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED = 54114, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF = 55711, SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED = 54045, + SPELL_HUNTER_PIERCING_SHOTS = 63468, SPELL_HUNTER_READINESS = 23989, SPELL_HUNTER_SNIPER_TRAINING_R1 = 53302, SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1 = 64418, + SPELL_HUNTER_T9_4P_GREATNESS = 68130, SPELL_HUNTER_VICIOUS_VIPER = 61609, SPELL_HUNTER_VIPER_ATTACK_SPEED = 60144, - SPELL_DRAENEI_GIFT_OF_THE_NAARU = 59543 + SPELL_DRAENEI_GIFT_OF_THE_NAARU = 59543, + SPELL_ROAR_OF_SACRIFICE_TRIGGERED = 67481 }; // 13161 - Aspect of the Beast @@ -192,8 +196,8 @@ class spell_hun_chimera_shot : public SpellScriptLoader { uint32 spellId = 0; int32 basePoint = 0; - Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); - for (Unit::AuraApplicationMap::iterator i = Auras.begin(); i != Auras.end(); ++i) + Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras(); + for (Unit::AuraApplicationMap::const_iterator i = auras.begin(); i != auras.end(); ++i) { Aura* aura = i->second->GetBase(); if (aura->GetCasterGUID() != caster->GetGUID()) @@ -296,6 +300,68 @@ class spell_hun_disengage : public SpellScriptLoader } }; +// 56841 - Glyph of Arcane Shot +class spell_hun_glyph_of_arcane_shot : public SpellScriptLoader +{ + public: + spell_hun_glyph_of_arcane_shot() : SpellScriptLoader("spell_hun_glyph_of_arcane_shot") { } + + class spell_hun_glyph_of_arcane_shot_AuraScript : public AuraScript + { + PrepareAuraScript(spell_hun_glyph_of_arcane_shot_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_GLYPH_OF_ARCANE_SHOT)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (Unit* procTarget = eventInfo.GetProcTarget()) + { + Unit::AuraApplicationMap const& auras = procTarget->GetAppliedAuras(); + for (Unit::AuraApplicationMap::const_iterator i = auras.begin(); i != auras.end(); ++i) + { + Aura const* aura = i->second->GetBase(); + if (aura->GetCasterGUID() != GetTarget()->GetGUID()) + continue; + // Search only Serpent Sting, Viper Sting, Scorpid Sting, Wyvern Sting + if (aura->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_HUNTER + && aura->GetSpellInfo()->SpellFamilyFlags.HasFlag(0xC000, 0x1080)) + return true; + } + } + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + SpellInfo const* procSpell = eventInfo.GetSpellInfo(); + if (!procSpell) + return; + + int32 mana = procSpell->CalcPowerCost(GetTarget(), procSpell->GetSchoolMask()); + ApplyPct(mana, aurEff->GetAmount()); + + GetTarget()->CastCustomSpell(SPELL_HUNTER_GLYPH_OF_ARCANE_SHOT, SPELLVALUE_BASE_POINT0, mana, GetTarget()); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_hun_glyph_of_arcane_shot_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_hun_glyph_of_arcane_shot_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_hun_glyph_of_arcane_shot_AuraScript(); + } +}; + // -19572 - Improved Mend Pet class spell_hun_improved_mend_pet : public SpellScriptLoader { @@ -336,6 +402,7 @@ class spell_hun_improved_mend_pet : public SpellScriptLoader return new spell_hun_improved_mend_pet_AuraScript(); } }; + // 53412 - Invigoration class spell_hun_invigoration : public SpellScriptLoader { @@ -640,6 +707,63 @@ class spell_hun_pet_heart_of_the_phoenix : public SpellScriptLoader } }; +// -53234 - Piercing Shots +class spell_hun_piercing_shots : public SpellScriptLoader +{ +public: + spell_hun_piercing_shots() : SpellScriptLoader("spell_hun_piercing_shots") { } + + class spell_hun_piercing_shots_AuraScript : public AuraScript + { + PrepareAuraScript(spell_hun_piercing_shots_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PIERCING_SHOTS)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetActionTarget()) + return true; + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + Unit* caster = eventInfo.GetActor(); + Unit* target = eventInfo.GetActionTarget(); + + if (DamageInfo* dmgInfo = eventInfo.GetDamageInfo()) + { + SpellInfo const* piercingShots = sSpellMgr->AssertSpellInfo(SPELL_HUNTER_PIERCING_SHOTS); + int32 duration = piercingShots->GetMaxDuration(); + uint32 amplitude = piercingShots->Effects[EFFECT_0].Amplitude; + uint32 dmg = dmgInfo->GetDamage(); + + uint32 bp = CalculatePct(int32(dmg), aurEff->GetAmount()) / (duration / int32(amplitude)); + bp += target->GetRemainingPeriodicAmount(target->GetGUID(), SPELL_HUNTER_PIERCING_SHOTS, SPELL_AURA_PERIODIC_DAMAGE); + + caster->CastCustomSpell(SPELL_HUNTER_PIERCING_SHOTS, SPELLVALUE_BASE_POINT0, bp, target, true, nullptr, aurEff); + } + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_hun_piercing_shots_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_hun_piercing_shots_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_hun_piercing_shots_AuraScript(); + } +}; + // 56654, 58882 - Rapid Recuperation class spell_hun_rapid_recuperation : public SpellScriptLoader { @@ -699,7 +823,7 @@ class spell_hun_readiness : public SpellScriptLoader // immediately finishes the cooldown on your other Hunter abilities except Bestial Wrath GetCaster()->GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); ///! If spellId in cooldown map isn't valid, the above will return a null pointer. if (spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && @@ -724,6 +848,49 @@ class spell_hun_readiness : public SpellScriptLoader } }; +// 53480 - Roar of Sacrifice +class spell_hun_roar_of_sacrifice : public SpellScriptLoader +{ + public: + spell_hun_roar_of_sacrifice() : SpellScriptLoader("spell_hun_roar_of_sacrifice") { } + + class spell_hun_roar_of_sacrifice_AuraScript : public AuraScript + { + PrepareAuraScript(spell_hun_roar_of_sacrifice_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_ROAR_OF_SACRIFICE_TRIGGERED)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + return GetCaster() && (eventInfo.GetDamageInfo()->GetSchoolMask() & GetEffect(EFFECT_1)->GetMiscValue()) != 0; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + uint32 damage = CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount()); + eventInfo.GetActor()->CastCustomSpell(SPELL_ROAR_OF_SACRIFICE_TRIGGERED, SPELLVALUE_BASE_POINT0, damage, GetCaster(), TRIGGERED_FULL_MASK, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_hun_roar_of_sacrifice_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_hun_roar_of_sacrifice_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_DUMMY); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_hun_roar_of_sacrifice_AuraScript(); + } +}; + // 37506 - Scatter Shot class spell_hun_scatter_shot : public SpellScriptLoader { @@ -903,6 +1070,51 @@ class spell_hun_target_only_pet_and_owner : public SpellScriptLoader } }; +// 67151 - T9 4P Bonus +class spell_hun_t9_4p_bonus : public SpellScriptLoader +{ +public: + spell_hun_t9_4p_bonus() : SpellScriptLoader("spell_hun_t9_4p_bonus") { } + + class spell_hun_t9_4p_bonus_AuraScript : public AuraScript + { + PrepareAuraScript(spell_hun_t9_4p_bonus_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_T9_4P_GREATNESS)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetActor()->GetTypeId() == TYPEID_PLAYER && eventInfo.GetActor()->ToPlayer()->GetPet()) + return true; + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + Unit* caster = eventInfo.GetActor(); + + caster->CastSpell(caster->ToPlayer()->GetPet(), SPELL_HUNTER_T9_4P_GREATNESS, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_hun_t9_4p_bonus_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_hun_t9_4p_bonus_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_hun_t9_4p_bonus_AuraScript(); + } +}; + // 60144 - Viper Attack Speed class spell_hun_viper_attack_speed : public SpellScriptLoader { @@ -952,6 +1164,7 @@ void AddSC_hunter_spell_scripts() new spell_hun_ascpect_of_the_viper(); new spell_hun_chimera_shot(); new spell_hun_disengage(); + new spell_hun_glyph_of_arcane_shot(); new spell_hun_improved_mend_pet(); new spell_hun_invigoration(); new spell_hun_last_stand_pet(); @@ -960,11 +1173,14 @@ void AddSC_hunter_spell_scripts() new spell_hun_misdirection_proc(); new spell_hun_pet_carrion_feeder(); new spell_hun_pet_heart_of_the_phoenix(); + new spell_hun_piercing_shots(); new spell_hun_rapid_recuperation(); new spell_hun_readiness(); + new spell_hun_roar_of_sacrifice(); new spell_hun_scatter_shot(); new spell_hun_sniper_training(); new spell_hun_tame_beast(); new spell_hun_target_only_pet_and_owner(); + new spell_hun_t9_4p_bonus(); new spell_hun_viper_attack_speed(); } diff --git a/src/server/scripts/Spells/spell_item.cpp b/src/server/scripts/Spells/spell_item.cpp index 0abff255e4b..5a6bb78eb10 100644 --- a/src/server/scripts/Spells/spell_item.cpp +++ b/src/server/scripts/Spells/spell_item.cpp @@ -201,6 +201,55 @@ class spell_item_blessing_of_ancient_kings : public SpellScriptLoader } }; +// 47770 - Roll Dice +class spell_item_decahedral_dwarven_dice : public SpellScriptLoader +{ + public: + spell_item_decahedral_dwarven_dice() : SpellScriptLoader("spell_item_decahedral_dwarven_dice") { } + + class spell_item_decahedral_dwarven_dice_SpellScript : public SpellScript + { + PrepareSpellScript(spell_item_decahedral_dwarven_dice_SpellScript); + + enum + { + TEXT_DECAHEDRAL_DWARVEN_DICE = 26147 + }; + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sObjectMgr->GetBroadcastText(TEXT_DECAHEDRAL_DWARVEN_DICE)) + return false; + return true; + } + + bool Load() override + { + return GetCaster()->GetTypeId() == TYPEID_PLAYER; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + GetCaster()->TextEmote(TEXT_DECAHEDRAL_DWARVEN_DICE, GetHitUnit()); + + static uint32 const minimum = 1; + static uint32 const maximum = 100; + + GetCaster()->ToPlayer()->DoRandomRoll(minimum, maximum); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_item_decahedral_dwarven_dice_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_item_decahedral_dwarven_dice_SpellScript(); + } +}; + // 8342 - Defibrillate (Goblin Jumper Cables) have 33% chance on success // 22999 - Defibrillate (Goblin Jumper Cables XL) have 50% chance on success // 54732 - Defibrillate (Gnomish Army Knife) have 67% chance on success @@ -1319,6 +1368,57 @@ class spell_item_underbelly_elixir : public SpellScriptLoader } }; +// 47776 - Roll 'dem Bones +class spell_item_worn_troll_dice : public SpellScriptLoader +{ + public: + spell_item_worn_troll_dice() : SpellScriptLoader("spell_item_worn_troll_dice") { } + + class spell_item_worn_troll_dice_SpellScript : public SpellScript + { + PrepareSpellScript(spell_item_worn_troll_dice_SpellScript); + + enum + { + TEXT_WORN_TROLL_DICE = 26152 + }; + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sObjectMgr->GetBroadcastText(TEXT_WORN_TROLL_DICE)) + return false; + return true; + } + + bool Load() override + { + return GetCaster()->GetTypeId() == TYPEID_PLAYER; + } + + void HandleScript(SpellEffIndex /*effIndex*/) + { + GetCaster()->TextEmote(TEXT_WORN_TROLL_DICE, GetHitUnit()); + + static uint32 const minimum = 1; + static uint32 const maximum = 6; + + // roll twice + GetCaster()->ToPlayer()->DoRandomRoll(minimum, maximum); + GetCaster()->ToPlayer()->DoRandomRoll(minimum, maximum); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_item_worn_troll_dice_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_item_worn_troll_dice_SpellScript(); + } +}; + enum AirRifleSpells { SPELL_AIR_RIFLE_HOLD_VISUAL = 65582, @@ -1803,7 +1903,7 @@ class spell_item_crystal_prison_dummy_dnd : public SpellScriptLoader 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(NULL))); + GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, *target, G3D::Quat(), uint32(target->GetRespawnTime()-time(NULL))); target->DespawnOrUnsummon(); } } @@ -2631,6 +2731,70 @@ public: } }; +enum SoulPreserver +{ + SPELL_SOUL_PRESERVER_DRUID = 60512, + SPELL_SOUL_PRESERVER_PALADIN = 60513, + SPELL_SOUL_PRESERVER_PRIEST = 60514, + SPELL_SOUL_PRESERVER_SHAMAN = 60515, +}; + +class spell_item_soul_preserver : public SpellScriptLoader +{ +public: + spell_item_soul_preserver() : SpellScriptLoader("spell_item_soul_preserver") { } + + class spell_item_soul_preserver_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_soul_preserver_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_DRUID) || + !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_PALADIN) || + !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_PRIEST) || + !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_SHAMAN)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + + switch (caster->getClass()) + { + case CLASS_DRUID: + caster->CastSpell(caster, SPELL_SOUL_PRESERVER_DRUID, true, nullptr, aurEff); + break; + case CLASS_PALADIN: + caster->CastSpell(caster, SPELL_SOUL_PRESERVER_PALADIN, true, nullptr, aurEff); + break; + case CLASS_PRIEST: + caster->CastSpell(caster, SPELL_SOUL_PRESERVER_PRIEST, true, nullptr, aurEff); + break; + case CLASS_SHAMAN: + caster->CastSpell(caster, SPELL_SOUL_PRESERVER_SHAMAN, true, nullptr, aurEff); + break; + default: + break; + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_soul_preserver_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_soul_preserver_AuraScript(); + } +}; + class spell_item_toy_train_set_pulse : public SpellScriptLoader { public: @@ -2668,6 +2832,336 @@ public: } }; +enum DeathChoiceSpells +{ + SPELL_DEATH_CHOICE_NORMAL_AURA = 67702, + SPELL_DEATH_CHOICE_NORMAL_AGILITY = 67703, + SPELL_DEATH_CHOICE_NORMAL_STRENGTH = 67708, + SPELL_DEATH_CHOICE_HEROIC_AURA = 67771, + SPELL_DEATH_CHOICE_HEROIC_AGILITY = 67772, + SPELL_DEATH_CHOICE_HEROIC_STRENGTH = 67773 +}; + +class spell_item_death_choice : public SpellScriptLoader +{ +public: + spell_item_death_choice() : SpellScriptLoader("spell_item_death_choice") { } + + class spell_item_death_choice_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_death_choice_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_NORMAL_STRENGTH) || + !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_NORMAL_AGILITY) || + !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_HEROIC_STRENGTH) || + !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_HEROIC_AGILITY)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + float str = caster->GetStat(STAT_STRENGTH); + float agi = caster->GetStat(STAT_AGILITY); + + switch (aurEff->GetId()) + { + case SPELL_DEATH_CHOICE_NORMAL_AURA: + { + if (str > agi) + caster->CastSpell(caster, SPELL_DEATH_CHOICE_NORMAL_STRENGTH, true, nullptr, aurEff); + else + caster->CastSpell(caster, SPELL_DEATH_CHOICE_NORMAL_AGILITY, true, nullptr, aurEff); + break; + } + case SPELL_DEATH_CHOICE_HEROIC_AURA: + { + if (str > agi) + caster->CastSpell(caster, SPELL_DEATH_CHOICE_HEROIC_STRENGTH, true, nullptr, aurEff); + else + caster->CastSpell(caster, SPELL_DEATH_CHOICE_HEROIC_AGILITY, true, nullptr, aurEff); + break; + } + default: + break; + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_death_choice_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_death_choice_AuraScript(); + } +}; + +enum TrinketStackSpells +{ + SPELL_LIGHTNING_CAPACITOR_AURA = 37657, // Lightning Capacitor + SPELL_LIGHTNING_CAPACITOR_STACK = 37658, + SPELL_LIGHTNING_CAPACITOR_TRIGGER = 37661, + SPELL_THUNDER_CAPACITOR_AURA = 54841, // Thunder Capacitor + SPELL_THUNDER_CAPACITOR_STACK = 54842, + SPELL_THUNDER_CAPACITOR_TRIGGER = 54843, + SPELL_TOC25_CASTER_TRINKET_NORMAL_AURA = 67712, // Item - Coliseum 25 Normal Caster Trinket + SPELL_TOC25_CASTER_TRINKET_NORMAL_STACK = 67713, + SPELL_TOC25_CASTER_TRINKET_NORMAL_TRIGGER = 67714, + SPELL_TOC25_CASTER_TRINKET_HEROIC_AURA = 67758, // Item - Coliseum 25 Heroic Caster Trinket + SPELL_TOC25_CASTER_TRINKET_HEROIC_STACK = 67759, + SPELL_TOC25_CASTER_TRINKET_HEROIC_TRIGGER = 67760, +}; + +class spell_item_trinket_stack : public SpellScriptLoader +{ +public: + spell_item_trinket_stack(char const* scriptName, uint32 stackSpell, uint32 triggerSpell) : SpellScriptLoader(scriptName), + _stackSpell(stackSpell), _triggerSpell(triggerSpell) + { + } + + class spell_item_trinket_stack_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_trinket_stack_AuraScript); + + public: + spell_item_trinket_stack_AuraScript(uint32 stackSpell, uint32 triggerSpell) : _stackSpell(stackSpell), _triggerSpell(triggerSpell) + { + } + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(_stackSpell) || !sSpellMgr->GetSpellInfo(_triggerSpell)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + + caster->CastSpell(caster, _stackSpell, true, nullptr, aurEff); // cast the stack + + Aura* dummy = caster->GetAura(_stackSpell); // retrieve aura + + //dont do anything if it's not the right amount of stacks; + if (!dummy || dummy->GetStackAmount() < aurEff->GetAmount()) + return; + + // if right amount, remove the aura and cast real trigger + caster->RemoveAurasDueToSpell(_stackSpell); + if (Unit* target = eventInfo.GetActionTarget()) + caster->CastSpell(target, _triggerSpell, true, nullptr, aurEff); + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_trinket_stack_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + + private: + uint32 _stackSpell; + uint32 _triggerSpell; + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_trinket_stack_AuraScript(_stackSpell, _triggerSpell); + } + +private: + uint32 _stackSpell; + uint32 _triggerSpell; +}; + +// 57345 - Darkmoon Card: Greatness +enum DarkmoonCardSpells +{ + SPELL_DARKMOON_CARD_STRENGHT = 60229, + SPELL_DARKMOON_CARD_AGILITY = 60233, + SPELL_DARKMOON_CARD_INTELLECT = 60234, + SPELL_DARKMOON_CARD_SPIRIT = 60235, +}; + +class spell_item_darkmoon_card_greatness : public SpellScriptLoader +{ +public: + spell_item_darkmoon_card_greatness() : SpellScriptLoader("spell_item_darkmoon_card_greatness") { } + + class spell_item_darkmoon_card_greatness_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_darkmoon_card_greatness_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_STRENGHT) || + !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_AGILITY) || + !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_INTELLECT) || + !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_SPIRIT)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + float str = caster->GetStat(STAT_STRENGTH); + float agi = caster->GetStat(STAT_AGILITY); + float intl = caster->GetStat(STAT_INTELLECT); + float spi = caster->GetStat(STAT_SPIRIT); + float stat = 0.0f; + + uint32 spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + + if (str > stat) + { + spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + stat = str; + } + + if (agi > stat) + { + spellTrigger = SPELL_DARKMOON_CARD_AGILITY; + stat = agi; + } + + if (intl > stat) + { + spellTrigger = SPELL_DARKMOON_CARD_INTELLECT; + stat = intl; + } + + if (spi > stat) + { + spellTrigger = SPELL_DARKMOON_CARD_SPIRIT; + stat = spi; + } + + caster->CastSpell(caster, spellTrigger, true, nullptr, aurEff); + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_darkmoon_card_greatness_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_darkmoon_card_greatness_AuraScript(); + } +}; + +// 43820 - Amani Charm of the Witch Doctor +enum CharmWitchDoctor +{ + SPELL_CHARM_WITCH_DOCTOR_PROC = 43821 +}; + +class spell_item_charm_witch_doctor : public SpellScriptLoader +{ +public: + spell_item_charm_witch_doctor() : SpellScriptLoader("spell_item_charm_witch_doctor") { } + + class spell_item_charm_witch_doctor_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_charm_witch_doctor_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_CHARM_WITCH_DOCTOR_PROC)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + Unit* target = eventInfo.GetActionTarget(); + + if (target) + { + int32 bp = CalculatePct(target->GetCreateHealth(),aurEff->GetSpellInfo()->Effects[1].CalcValue()); + caster->CastCustomSpell(target, SPELL_CHARM_WITCH_DOCTOR_PROC, &bp, nullptr, nullptr, true, nullptr, aurEff); + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_charm_witch_doctor_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_charm_witch_doctor_AuraScript(); + } +}; + +// 27522,40336 - Mana Drain +enum ManaDrainSpells +{ + SPELL_MANA_DRAIN_ENERGIZE = 29471, + SPELL_MANA_DRAIN_LEECH = 27526 +}; + +class spell_item_mana_drain : public SpellScriptLoader +{ +public: + spell_item_mana_drain() : SpellScriptLoader("spell_item_mana_drain") { } + + class spell_item_mana_drain_AuraScript : public AuraScript + { + PrepareAuraScript(spell_item_mana_drain_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_ENERGIZE) + || !sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_LEECH)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + Unit* caster = eventInfo.GetActor(); + Unit* target = eventInfo.GetActionTarget(); + + if (caster->IsAlive()) + caster->CastSpell(caster, SPELL_MANA_DRAIN_ENERGIZE, true, nullptr, aurEff); + + if (target && target->IsAlive()) + caster->CastSpell(target, SPELL_MANA_DRAIN_LEECH, true, nullptr, aurEff); + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_item_mana_drain_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_item_mana_drain_AuraScript(); + } +}; + void AddSC_item_spell_scripts() { // 23074 Arcanite Dragonling @@ -2682,6 +3176,7 @@ void AddSC_item_spell_scripts() new spell_item_aegis_of_preservation(); new spell_item_arcane_shroud(); new spell_item_blessing_of_ancient_kings(); + new spell_item_decahedral_dwarven_dice(); new spell_item_defibrillate("spell_item_goblin_jumper_cables", 67, SPELL_GOBLIN_JUMPER_CABLES_FAIL); new spell_item_defibrillate("spell_item_goblin_jumper_cables_xl", 50, SPELL_GOBLIN_JUMPER_CABLES_XL_FAIL); new spell_item_defibrillate("spell_item_gnomish_army_knife", 33); @@ -2706,6 +3201,7 @@ void AddSC_item_spell_scripts() new spell_item_six_demon_bag(); new spell_item_the_eye_of_diminution(); new spell_item_underbelly_elixir(); + new spell_item_worn_troll_dice(); new spell_item_red_rider_air_rifle(); new spell_item_create_heart_candy(); @@ -2736,5 +3232,14 @@ void AddSC_item_spell_scripts() new spell_item_chicken_cover(); new spell_item_muisek_vessel(); new spell_item_greatmothers_soulcatcher(); + new spell_item_soul_preserver(); new spell_item_toy_train_set_pulse(); + new spell_item_death_choice(); + new spell_item_trinket_stack("spell_item_lightning_capacitor", SPELL_LIGHTNING_CAPACITOR_STACK, SPELL_LIGHTNING_CAPACITOR_TRIGGER); + new spell_item_trinket_stack("spell_item_thunder_capacitor", SPELL_THUNDER_CAPACITOR_STACK, SPELL_THUNDER_CAPACITOR_TRIGGER); + new spell_item_trinket_stack("spell_item_toc25_normal_caster_trinket", SPELL_TOC25_CASTER_TRINKET_NORMAL_STACK, SPELL_TOC25_CASTER_TRINKET_NORMAL_TRIGGER); + new spell_item_trinket_stack("spell_item_toc25_heroic_caster_trinket", SPELL_TOC25_CASTER_TRINKET_HEROIC_STACK, SPELL_TOC25_CASTER_TRINKET_HEROIC_TRIGGER); + new spell_item_darkmoon_card_greatness(); + new spell_item_charm_witch_doctor(); + new spell_item_mana_drain(); } diff --git a/src/server/scripts/Spells/spell_mage.cpp b/src/server/scripts/Spells/spell_mage.cpp index d08968fbf55..bacbe31630c 100644 --- a/src/server/scripts/Spells/spell_mage.cpp +++ b/src/server/scripts/Spells/spell_mage.cpp @@ -29,6 +29,7 @@ enum MageSpells { + SPELL_MAGE_BLAZING_SPEED = 31643, SPELL_MAGE_BURNOUT = 29077, SPELL_MAGE_COLD_SNAP = 11958, SPELL_MAGE_FOCUS_MAGIC_PROC = 54648, @@ -116,6 +117,42 @@ class spell_mage_blast_wave : public SpellScriptLoader } }; +// -31641 - Blazing Speed +class spell_mage_blazing_speed : public SpellScriptLoader +{ +public: + spell_mage_blazing_speed() : SpellScriptLoader("spell_mage_blazing_speed") { } + + class spell_mage_blazing_speed_AuraScript : public AuraScript + { + PrepareAuraScript(spell_mage_blazing_speed_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_BLAZING_SPEED)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + if (Unit* target = eventInfo.GetActionTarget()) + target->CastSpell(target, SPELL_MAGE_BLAZING_SPEED, true, nullptr, aurEff); + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_mage_blazing_speed_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_mage_blazing_speed_AuraScript(); + } +}; + // -44449 - Burnout class spell_mage_burnout : public SpellScriptLoader { @@ -180,7 +217,7 @@ class spell_mage_cold_snap : public SpellScriptLoader { GetCaster()->GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); return spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (spellInfo->GetSchoolMask() & SPELL_SCHOOL_MASK_FROST) && spellInfo->Id != SPELL_MAGE_COLD_SNAP && spellInfo->GetRecoveryTime() > 0; }, true); @@ -405,7 +442,7 @@ class spell_mage_ignite : public SpellScriptLoader { PreventDefaultAction(); - SpellInfo const* igniteDot = sSpellMgr->EnsureSpellInfo(SPELL_MAGE_IGNITE); + SpellInfo const* igniteDot = sSpellMgr->AssertSpellInfo(SPELL_MAGE_IGNITE); int32 pct = 8 * GetSpellInfo()->GetRank(); int32 amount = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), pct) / igniteDot->GetMaxTicks()); @@ -647,6 +684,7 @@ class spell_mage_summon_water_elemental : public SpellScriptLoader void AddSC_mage_spell_scripts() { new spell_mage_blast_wave(); + new spell_mage_blazing_speed(); new spell_mage_burnout(); new spell_mage_cold_snap(); new spell_mage_fire_frost_ward(); diff --git a/src/server/scripts/Spells/spell_paladin.cpp b/src/server/scripts/Spells/spell_paladin.cpp index 8bd4b3eb070..6de95af8d8f 100644 --- a/src/server/scripts/Spells/spell_paladin.cpp +++ b/src/server/scripts/Spells/spell_paladin.cpp @@ -37,6 +37,7 @@ enum PaladinSpells SPELL_PALADIN_HOLY_SHOCK_R1 = 20473, SPELL_PALADIN_HOLY_SHOCK_R1_DAMAGE = 25912, SPELL_PALADIN_HOLY_SHOCK_R1_HEALING = 25914, + SPELL_PALADIN_ILLUMINATION_ENERGIZE = 20272, SPELL_PALADIN_BLESSING_OF_LOWER_CITY_DRUID = 37878, SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PALADIN = 37879, @@ -871,6 +872,61 @@ class spell_pal_holy_shock : public SpellScriptLoader } }; +// -20210 - Illumination +class spell_pal_illumination : public SpellScriptLoader +{ +public: + spell_pal_illumination() : SpellScriptLoader("spell_pal_illumination") { } + + class spell_pal_illumination_AuraScript : public AuraScript + { + PrepareAuraScript(spell_pal_illumination_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_SHOCK_R1_HEALING) || + !sSpellMgr->GetSpellInfo(SPELL_PALADIN_ILLUMINATION_ENERGIZE) || + !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_SHOCK_R1)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + + // this script is valid only for the Holy Shock procs of illumination + if (eventInfo.GetHealInfo() && eventInfo.GetHealInfo()->GetSpellInfo()) + { + SpellInfo const* originalSpell = nullptr; + + // if proc comes from the Holy Shock heal, need to get mana cost of original spell - else it's the original heal itself + if (eventInfo.GetHealInfo()->GetSpellInfo()->SpellFamilyFlags[1] & 0x00010000) + originalSpell = sSpellMgr->GetSpellInfo(sSpellMgr->GetSpellWithRank(SPELL_PALADIN_HOLY_SHOCK_R1, eventInfo.GetHealInfo()->GetSpellInfo()->GetRank())); + else + originalSpell = eventInfo.GetHealInfo()->GetSpellInfo(); + + if (originalSpell && aurEff->GetSpellInfo()) + { + Unit* target = eventInfo.GetActor(); // Paladin is the target of the energize + uint32 bp = CalculatePct(originalSpell->CalcPowerCost(target, originalSpell->GetSchoolMask()), aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue()); + target->CastCustomSpell(SPELL_PALADIN_ILLUMINATION_ENERGIZE, SPELLVALUE_BASE_POINT0, bp, target, true, nullptr, aurEff); + } + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_pal_illumination_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_pal_illumination_AuraScript(); + } +}; + // Maybe this is incorrect // These spells should always be cast on login, regardless of whether the player has the talent or not @@ -1195,7 +1251,7 @@ class spell_pal_light_s_beacon : public SpellScriptLoader if (!procSpell) return; - uint32 healSpellId = procSpell->IsRankOf(sSpellMgr->EnsureSpellInfo(SPELL_PALADIN_HOLY_LIGHT)) ? SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_1 : SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_3; + uint32 healSpellId = procSpell->IsRankOf(sSpellMgr->AssertSpellInfo(SPELL_PALADIN_HOLY_LIGHT)) ? SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_1 : SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_3; uint32 heal = CalculatePct(eventInfo.GetHealInfo()->GetHeal(), aurEff->GetAmount()); Unit* beaconTarget = GetCaster(); @@ -1393,6 +1449,7 @@ void AddSC_paladin_spell_scripts() new spell_pal_hand_of_sacrifice(); new spell_pal_hand_of_salvation(); new spell_pal_holy_shock(); + new spell_pal_illumination(); new spell_pal_improved_aura("spell_pal_improved_concentraction_aura", SPELL_PALADIN_IMPROVED_CONCENTRACTION_AURA); new spell_pal_improved_aura("spell_pal_improved_devotion_aura", SPELL_PALADIN_IMPROVED_DEVOTION_AURA); new spell_pal_improved_aura("spell_pal_sanctified_retribution", SPELL_PALADIN_SANCTIFIED_RETRIBUTION_AURA); diff --git a/src/server/scripts/Spells/spell_pet.cpp b/src/server/scripts/Spells/spell_pet.cpp index 7393a7d3bcb..cde291cd82b 100644 --- a/src/server/scripts/Spells/spell_pet.cpp +++ b/src/server/scripts/Spells/spell_pet.cpp @@ -916,7 +916,7 @@ public: if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value AddPct(mod, spellInfo->Effects[EFFECT_0].CalcValue()); } @@ -959,7 +959,7 @@ public: if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } @@ -989,7 +989,7 @@ public: if (itr != pet->ToPet()->m_spells.end()) // If pet has Wild Hunt { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); // Then get the SpellProto and add the dummy effect value mod += CalculatePct(1.0f, spellInfo->Effects[EFFECT_1].CalcValue()); } diff --git a/src/server/scripts/Spells/spell_priest.cpp b/src/server/scripts/Spells/spell_priest.cpp index ecf5b7b5acf..9e2d265aa9c 100644 --- a/src/server/scripts/Spells/spell_priest.cpp +++ b/src/server/scripts/Spells/spell_priest.cpp @@ -29,6 +29,7 @@ enum PriestSpells { + SPELL_PRIEST_BLESSED_RECOVERY_R1 = 27813, SPELL_PRIEST_DIVINE_AEGIS = 47753, SPELL_PRIEST_EMPOWERED_RENEW = 63544, SPELL_PRIEST_GLYPH_OF_CIRCLE_OF_HEALING = 55675, @@ -88,6 +89,50 @@ class RaidCheck Unit const* _caster; }; +// -27811 - Blessed Recovery +class spell_pri_blessed_recovery : public SpellScriptLoader +{ +public: + spell_pri_blessed_recovery() : SpellScriptLoader("spell_pri_blessed_recovery") { } + + class spell_pri_blessed_recovery_AuraScript : public AuraScript + { + PrepareAuraScript(spell_pri_blessed_recovery_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_BLESSED_RECOVERY_R1)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + if (DamageInfo* dmgInfo = eventInfo.GetDamageInfo()) + { + if (Unit* target = eventInfo.GetActionTarget()) + { + uint32 triggerSpell = sSpellMgr->GetSpellWithRank(SPELL_PRIEST_BLESSED_RECOVERY_R1, aurEff->GetSpellInfo()->GetRank()); + uint32 bp = CalculatePct(int32(dmgInfo->GetDamage()), aurEff->GetAmount()) / 3; + bp += target->GetRemainingPeriodicAmount(target->GetGUID(), triggerSpell, SPELL_AURA_PERIODIC_HEAL); + target->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, bp, target, true, nullptr, aurEff); + } + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_pri_blessed_recovery_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_pri_blessed_recovery_AuraScript(); + } +}; + // -34861 - Circle of Healing class spell_pri_circle_of_healing : public SpellScriptLoader { @@ -236,7 +281,7 @@ class spell_pri_glyph_of_prayer_of_healing : public SpellScriptLoader { PreventDefaultAction(); - SpellInfo const* triggeredSpellInfo = sSpellMgr->EnsureSpellInfo(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL); + SpellInfo const* triggeredSpellInfo = sSpellMgr->AssertSpellInfo(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL); int32 heal = int32(CalculatePct(int32(eventInfo.GetHealInfo()->GetHeal()), aurEff->GetAmount()) / triggeredSpellInfo->GetMaxTicks()); GetTarget()->CastCustomSpell(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL, SPELLVALUE_BASE_POINT0, heal, eventInfo.GetProcTarget(), true, NULL, aurEff); } @@ -869,6 +914,7 @@ class spell_pri_vampiric_touch : public SpellScriptLoader void AddSC_priest_spell_scripts() { + new spell_pri_blessed_recovery(); new spell_pri_circle_of_healing(); new spell_pri_divine_aegis(); new spell_pri_divine_hymn(); diff --git a/src/server/scripts/Spells/spell_quest.cpp b/src/server/scripts/Spells/spell_quest.cpp index 3121a18734d..715e4d4ed2d 100644 --- a/src/server/scripts/Spells/spell_quest.cpp +++ b/src/server/scripts/Spells/spell_quest.cpp @@ -1080,9 +1080,7 @@ enum RedSnapperVeryTasty ITEM_RED_SNAPPER = 23614, SPELL_CAST_NET = 29866, - SPELL_NEW_SUMMON_TEST = 49214, - - GO_SCHOOL_OF_RED_SNAPPER = 181616 + SPELL_NEW_SUMMON_TEST = 49214 }; class spell_q9452_cast_net: public SpellScriptLoader @@ -1099,15 +1097,6 @@ class spell_q9452_cast_net: public SpellScriptLoader return GetCaster()->GetTypeId() == TYPEID_PLAYER; } - SpellCastResult CheckCast() - { - GameObject* go = GetCaster()->FindNearestGameObject(GO_SCHOOL_OF_RED_SNAPPER, 3.0f); - if (!go || go->GetRespawnTime()) - return SPELL_FAILED_REQUIRES_SPELL_FOCUS; - - return SPELL_CAST_OK; - } - void HandleDummy(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); @@ -1127,7 +1116,6 @@ class spell_q9452_cast_net: public SpellScriptLoader void Register() override { - OnCheckCast += SpellCheckCastFn(spell_q9452_cast_net_SpellScript::CheckCast); OnEffectHit += SpellEffectFn(spell_q9452_cast_net_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); OnEffectHitTarget += SpellEffectFn(spell_q9452_cast_net_SpellScript::HandleActiveObject, EFFECT_1, SPELL_EFFECT_ACTIVATE_OBJECT); } @@ -1707,7 +1695,7 @@ enum Quest13291_13292_13239_13261Data NPC_SKYTALON = 31583, NPC_DECOY = 31578, // Spells - SPELL_RIDE = 56687 + SPELL_RIDE = 59319 }; class spell_q13291_q13292_q13239_q13261_frostbrood_skytalon_grab_decoy : public SpellScriptLoader @@ -2482,6 +2470,33 @@ class spell_q13665_q13790_bested_trigger : public SpellScriptLoader } }; +// herald of war and life without regret portal spells +class spell_59064_59439_portals : public SpellScriptLoader +{ +public: + spell_59064_59439_portals() : SpellScriptLoader("spell_59064_59439_portals") { } + + class spell_59064_59439_portals_SpellScript : public SpellScript + { + PrepareSpellScript(spell_59064_59439_portals_SpellScript); + + void HandleScript(SpellEffIndex /*effIndex*/) + { + GetHitUnit()->CastSpell(GetHitUnit(), uint32(GetEffectValue())); + } + + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_59064_59439_portals_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const override + { + return new spell_59064_59439_portals_SpellScript(); + } +}; + void AddSC_quest_spell_scripts() { new spell_q55_sacred_cleansing(); @@ -2542,4 +2557,5 @@ void AddSC_quest_spell_scripts() new spell_q10929_fumping(); new spell_q12414_hand_over_reins(); new spell_q13665_q13790_bested_trigger(); + new spell_59064_59439_portals(); } diff --git a/src/server/scripts/Spells/spell_rogue.cpp b/src/server/scripts/Spells/spell_rogue.cpp index 9b577d4e140..1abb6741e0d 100644 --- a/src/server/scripts/Spells/spell_rogue.cpp +++ b/src/server/scripts/Spells/spell_rogue.cpp @@ -43,7 +43,8 @@ enum RogueSpells SPELL_ROGUE_TRICKS_OF_THE_TRADE_PROC = 59628, SPELL_ROGUE_HONOR_AMONG_THIEVES = 51698, SPELL_ROGUE_HONOR_AMONG_THIEVES_PROC = 52916, - SPELL_ROGUE_HONOR_AMONG_THIEVES_2 = 51699 + SPELL_ROGUE_HONOR_AMONG_THIEVES_2 = 51699, + SPELL_ROGUE_T10_2P_BONUS = 70804, }; // 13877, 33735, (check 51211, 65956) - Blade Flurry @@ -450,7 +451,7 @@ class spell_rog_preparation : public SpellScriptLoader Unit* caster = GetCaster(); caster->GetSpellHistory()->ResetCooldowns([caster](SpellHistory::CooldownStorageType::iterator itr) -> bool { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); if (spellInfo->SpellFamilyName != SPELLFAMILY_ROGUE) return false; @@ -843,6 +844,40 @@ public: } }; +// 70805 - Rogue T10 2P Bonus -- THIS SHOULD BE REMOVED WITH NEW PROC SYSTEM. +class spell_rog_t10_2p_bonus : public SpellScriptLoader +{ +public: + spell_rog_t10_2p_bonus() : SpellScriptLoader("spell_rog_t10_2p_bonus") { } + + class spell_rog_t10_2p_bonus_AuraScript : public AuraScript + { + PrepareAuraScript(spell_rog_t10_2p_bonus_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_T10_2P_BONUS)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + return eventInfo.GetActor() == eventInfo.GetActionTarget(); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_rog_t10_2p_bonus_AuraScript::CheckProc); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_rog_t10_2p_bonus_AuraScript(); + } +}; + void AddSC_rogue_spell_scripts() { new spell_rog_blade_flurry(); @@ -858,4 +893,5 @@ void AddSC_rogue_spell_scripts() new spell_rog_tricks_of_the_trade_proc(); new spell_rog_honor_among_thieves(); new spell_rog_honor_among_thieves_proc(); + new spell_rog_t10_2p_bonus(); } diff --git a/src/server/scripts/Spells/spell_script_loader.cpp b/src/server/scripts/Spells/spell_script_loader.cpp new file mode 100644 index 00000000000..b2c8d6663fa --- /dev/null +++ b/src/server/scripts/Spells/spell_script_loader.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +// This is where scripts' loading functions should be declared: +void AddSC_deathknight_spell_scripts(); +void AddSC_druid_spell_scripts(); +void AddSC_generic_spell_scripts(); +void AddSC_hunter_spell_scripts(); +void AddSC_mage_spell_scripts(); +void AddSC_paladin_spell_scripts(); +void AddSC_priest_spell_scripts(); +void AddSC_rogue_spell_scripts(); +void AddSC_shaman_spell_scripts(); +void AddSC_warlock_spell_scripts(); +void AddSC_warrior_spell_scripts(); +void AddSC_quest_spell_scripts(); +void AddSC_item_spell_scripts(); +void AddSC_holiday_spell_scripts(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddSpellsScripts() +{ + AddSC_deathknight_spell_scripts(); + AddSC_druid_spell_scripts(); + AddSC_generic_spell_scripts(); + AddSC_hunter_spell_scripts(); + AddSC_mage_spell_scripts(); + AddSC_paladin_spell_scripts(); + AddSC_priest_spell_scripts(); + AddSC_rogue_spell_scripts(); + AddSC_shaman_spell_scripts(); + AddSC_warlock_spell_scripts(); + AddSC_warrior_spell_scripts(); + AddSC_quest_spell_scripts(); + AddSC_item_spell_scripts(); + AddSC_holiday_spell_scripts(); +} diff --git a/src/server/scripts/Spells/spell_shaman.cpp b/src/server/scripts/Spells/spell_shaman.cpp index 41e72b1388b..ad65c7c6ec7 100644 --- a/src/server/scripts/Spells/spell_shaman.cpp +++ b/src/server/scripts/Spells/spell_shaman.cpp @@ -48,8 +48,10 @@ enum ShamanSpells SPELL_SHAMAN_ITEM_MANA_SURGE = 23571, SPELL_SHAMAN_LAVA_FLOWS_R1 = 51480, SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1 = 64694, + SPELL_SHAMAN_LIGHTNING_SHIELD_R1 = 26364, SPELL_SHAMAN_MANA_SPRING_TOTEM_ENERGIZE = 52032, SPELL_SHAMAN_MANA_TIDE_TOTEM = 39609, + SPELL_SHAMAN_NATURE_GUARDIAN = 31616, SPELL_SHAMAN_SATED = 57724, SPELL_SHAMAN_STORM_EARTH_AND_FIRE = 51483, SPELL_SHAMAN_TOTEM_EARTHBIND_EARTHGRAB = 64695, @@ -671,7 +673,7 @@ class spell_sha_heroism : public SpellScriptLoader } }; -// 23551 - Lightning Shield +// 23551 - Lightning Shield T2 Bonus class spell_sha_item_lightning_shield : public SpellScriptLoader { public: @@ -706,7 +708,7 @@ class spell_sha_item_lightning_shield : public SpellScriptLoader } }; -// 23552 - Lightning Shield +// 23552 - Lightning Shield T2 Bonus class spell_sha_item_lightning_shield_trigger : public SpellScriptLoader { public: @@ -718,7 +720,7 @@ class spell_sha_item_lightning_shield_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_MANA_SURGE)) + if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE)) return false; return true; } @@ -753,7 +755,7 @@ class spell_sha_item_mana_surge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE)) + if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_MANA_SURGE)) return false; return true; } @@ -865,6 +867,51 @@ class spell_sha_lava_lash : public SpellScriptLoader } }; +// -324 - Lightning Shield +class spell_sha_lightning_shield : public SpellScriptLoader +{ +public: + spell_sha_lightning_shield() : SpellScriptLoader("spell_sha_lightning_shield") { } + + class spell_sha_lightning_shield_AuraScript : public AuraScript + { + PrepareAuraScript(spell_sha_lightning_shield_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LIGHTNING_SHIELD_R1)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetActionTarget()) + return true; + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + uint32 triggerSpell = sSpellMgr->GetSpellWithRank(SPELL_SHAMAN_LIGHTNING_SHIELD_R1, aurEff->GetSpellInfo()->GetRank()); + + eventInfo.GetActionTarget()->CastSpell(eventInfo.GetActor(), triggerSpell, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_sha_lightning_shield_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_sha_lightning_shield_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_sha_lightning_shield_AuraScript(); + } +}; + // 52031, 52033, 52034, 52035, 52036, 58778, 58779, 58780 - Mana Spring Totem class spell_sha_mana_spring_totem : public SpellScriptLoader { @@ -924,6 +971,7 @@ class spell_sha_mana_tide_totem : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* caster = GetCaster()) + { if (Unit* unitTarget = GetHitUnit()) { if (unitTarget->getPowerType() == POWER_MANA) @@ -938,6 +986,7 @@ class spell_sha_mana_tide_totem : public SpellScriptLoader caster->CastCustomSpell(unitTarget, SPELL_SHAMAN_MANA_TIDE_TOTEM, &effBasePoints0, NULL, NULL, true, NULL, NULL, GetOriginalCaster()->GetGUID()); } } + } } void Register() override @@ -952,6 +1001,56 @@ class spell_sha_mana_tide_totem : public SpellScriptLoader } }; +// -30881 - Nature's Guardian +class spell_sha_nature_guardian : public SpellScriptLoader +{ +public: + spell_sha_nature_guardian() : SpellScriptLoader("spell_sha_nature_guardian") { } + + class spell_sha_nature_guardian_AuraScript : public AuraScript + { + PrepareAuraScript(spell_sha_nature_guardian_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_NATURE_GUARDIAN)) + return false; + return true; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + int32 healthpct = aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue(); // %s2 - the 30% threshold for health + + if (Unit* target = eventInfo.GetActionTarget()) + { + if (target->HealthBelowPctDamaged(healthpct, eventInfo.GetDamageInfo()->GetDamage())) + { + + uint32 bp = CalculatePct(target->GetMaxHealth(), aurEff->GetAmount()); + target->CastCustomSpell(SPELL_SHAMAN_NATURE_GUARDIAN, SPELLVALUE_BASE_POINT0, bp, target, true, nullptr, aurEff); + + // Threat reduction is around 10% confirmed in retail and from wiki + Unit* attacker = eventInfo.GetActor(); + if (attacker->IsAlive()) + attacker->getThreatManager().modifyThreatPercent(target, -10); + } + } + } + + void Register() override + { + OnEffectProc += AuraEffectProcFn(spell_sha_nature_guardian_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_sha_nature_guardian_AuraScript(); + } +}; + // 6495 - Sentry Totem class spell_sha_sentry_totem : public SpellScriptLoader { @@ -1085,8 +1184,10 @@ void AddSC_shaman_spell_scripts() new spell_sha_item_mana_surge(); new spell_sha_item_t10_elemental_2p_bonus(); new spell_sha_lava_lash(); + new spell_sha_lightning_shield(); new spell_sha_mana_spring_totem(); new spell_sha_mana_tide_totem(); + new spell_sha_nature_guardian(); new spell_sha_sentry_totem(); new spell_sha_thunderstorm(); new spell_sha_totemic_mastery(); diff --git a/src/server/scripts/Spells/spell_warlock.cpp b/src/server/scripts/Spells/spell_warlock.cpp index 7cc6fe888e9..5e0074bf9f7 100644 --- a/src/server/scripts/Spells/spell_warlock.cpp +++ b/src/server/scripts/Spells/spell_warlock.cpp @@ -50,6 +50,12 @@ enum WarlockSpells SPELL_WARLOCK_IMPROVED_HEALTH_FUNNEL_BUFF_R2 = 60956, SPELL_WARLOCK_LIFE_TAP_ENERGIZE = 31818, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2 = 32553, + SPELL_WARLOCK_NETHER_PROTECTION_HOLY = 54370, + SPELL_WARLOCK_NETHER_PROTECTION_FIRE = 54371, + SPELL_WARLOCK_NETHER_PROTECTION_FROST = 54372, + SPELL_WARLOCK_NETHER_PROTECTION_ARCANE = 54373, + SPELL_WARLOCK_NETHER_PROTECTION_SHADOW = 54374, + SPELL_WARLOCK_NETHER_PROTECTION_NATURE = 54375, SPELL_WARLOCK_SOULSHATTER = 32835, SPELL_WARLOCK_SIPHON_LIFE_HEAL = 63106, SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL = 31117 @@ -271,7 +277,7 @@ class spell_warl_demonic_circle_summon : public SpellScriptLoader // WARLOCK_DEMONIC_CIRCLE_ALLOW_CAST; allowing him to cast the WARLOCK_DEMONIC_CIRCLE_TELEPORT. // If not in range remove the WARLOCK_DEMONIC_CIRCLE_ALLOW_CAST. - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(SPELL_WARLOCK_DEMONIC_CIRCLE_TELEPORT); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(SPELL_WARLOCK_DEMONIC_CIRCLE_TELEPORT); if (GetTarget()->IsWithinDist(circle, spellInfo->GetMaxRange(true))) { @@ -362,7 +368,7 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader break; case CREATURE_FAMILY_VOIDWALKER: { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER); int32 hp = int32(targetCreature->CountPctFromMaxHealth(GetCaster()->CalculateSpellDamage(targetCreature, spellInfo, 0))); targetCreature->CastCustomSpell(targetCreature, SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, &hp, NULL, NULL, true); //unitTarget->CastSpell(unitTarget, 54441, true); @@ -377,6 +383,8 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader case CREATURE_FAMILY_IMP: targetCreature->CastSpell(targetCreature, SPELL_WARLOCK_DEMONIC_EMPOWERMENT_IMP, true); break; + default: + break; } } } @@ -682,6 +690,95 @@ class spell_warl_life_tap : public SpellScriptLoader } }; +// -30299 - Nether Protection +class spell_warl_nether_protection : public SpellScriptLoader +{ +public: + spell_warl_nether_protection() : SpellScriptLoader("spell_warl_nether_protection") { } + + class spell_warl_nether_protection_AuraScript : public AuraScript + { + PrepareAuraScript(spell_warl_nether_protection_AuraScript); + + bool Validate(SpellInfo const* /*spellInfo*/) override + { + if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_HOLY) || + !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_FIRE) || + !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_FROST) || + !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_ARCANE) || + !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_SHADOW) || + !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_NATURE)) + return false; + return true; + } + + bool CheckProc(ProcEventInfo& eventInfo) + { + if (eventInfo.GetDamageInfo()) + { + switch (GetFirstSchoolInMask(eventInfo.GetDamageInfo()->GetSchoolMask())) + { + case SPELL_SCHOOL_HOLY: + case SPELL_SCHOOL_FIRE: + case SPELL_SCHOOL_NATURE: + case SPELL_SCHOOL_FROST: + case SPELL_SCHOOL_SHADOW: + case SPELL_SCHOOL_ARCANE: + return true; + default: + break; + } + } + + return false; + } + + void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) + { + PreventDefaultAction(); + uint32 triggerspell = 0; + + switch (GetFirstSchoolInMask(eventInfo.GetDamageInfo()->GetSchoolMask())) + { + case SPELL_SCHOOL_HOLY: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_HOLY; + break; + case SPELL_SCHOOL_FIRE: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_FIRE; + break; + case SPELL_SCHOOL_NATURE: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_NATURE; + break; + case SPELL_SCHOOL_FROST: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_FROST; + break; + case SPELL_SCHOOL_SHADOW: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_SHADOW; + break; + case SPELL_SCHOOL_ARCANE: + triggerspell = SPELL_WARLOCK_NETHER_PROTECTION_ARCANE; + break; + default: + return; + } + + if (Unit* target = eventInfo.GetActionTarget()) + target->CastSpell(target, triggerspell, true, nullptr, aurEff); + } + + void Register() override + { + DoCheckProc += AuraCheckProcFn(spell_warl_nether_protection_AuraScript::CheckProc); + OnEffectProc += AuraEffectProcFn(spell_warl_nether_protection_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_warl_nether_protection_AuraScript(); + } +}; + // 18541 - Ritual of Doom Effect class spell_warl_ritual_of_doom_effect : public SpellScriptLoader { @@ -917,6 +1014,7 @@ void AddSC_warlock_spell_scripts() new spell_warl_haunt(); new spell_warl_health_funnel(); new spell_warl_life_tap(); + new spell_warl_nether_protection(); new spell_warl_ritual_of_doom_effect(); new spell_warl_seed_of_corruption(); new spell_warl_shadow_ward(); diff --git a/src/server/scripts/Spells/spell_warrior.cpp b/src/server/scripts/Spells/spell_warrior.cpp index d224c234cb4..ea9ccc956e5 100644 --- a/src/server/scripts/Spells/spell_warrior.cpp +++ b/src/server/scripts/Spells/spell_warrior.cpp @@ -271,7 +271,7 @@ class spell_warr_deep_wounds : public SpellScriptLoader { ApplyPct(damage, 16 * GetSpellInfo()->GetRank()); - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC); uint32 ticks = uint32(spellInfo->GetDuration()) / spellInfo->Effects[EFFECT_0].Amplitude; // Add remaining ticks to damage done diff --git a/src/server/scripts/World/CMakeLists.txt b/src/server/scripts/World/CMakeLists.txt deleted file mode 100644 index 17b3f2d8492..00000000000 --- a/src/server/scripts/World/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB_RECURSE sources_World World/*.cpp World/*.h) - -set(scripts_STAT_SRCS - ${scripts_STAT_SRCS} - ${sources_World} -) - -message(" -> Prepared: World") diff --git a/src/server/scripts/World/boss_emerald_dragons.cpp b/src/server/scripts/World/boss_emerald_dragons.cpp index 1f89720803d..65dec74414b 100644 --- a/src/server/scripts/World/boss_emerald_dragons.cpp +++ b/src/server/scripts/World/boss_emerald_dragons.cpp @@ -205,7 +205,7 @@ class npc_dream_fog : public CreatureScript } // Seeping fog movement is slow enough for a player to be able to walk backwards and still outpace it me->SetWalk(true); - me->SetSpeed(MOVE_WALK, 0.75f); + me->SetSpeedRate(MOVE_WALK, 0.75f); } else _roamTimer -= diff; diff --git a/src/server/scripts/World/duel_reset.cpp b/src/server/scripts/World/duel_reset.cpp index 3c46255a1bf..b04f3ec0aa7 100644 --- a/src/server/scripts/World/duel_reset.cpp +++ b/src/server/scripts/World/duel_reset.cpp @@ -98,16 +98,16 @@ class DuelResetScript : public PlayerScript static void ResetSpellCooldowns(Player* player, bool onStartDuel) { - if (onStartDuel) + if (onStartDuel) { // remove cooldowns on spells that have < 10 min CD > 30 sec and has no onHold player->GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool { SpellHistory::Clock::time_point now = SpellHistory::Clock::now(); uint32 cooldownDuration = itr->second.CooldownEnd > now ? std::chrono::duration_cast<std::chrono::milliseconds>(itr->second.CooldownEnd - now).count() : 0; - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); - return spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS - && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); + return spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS + && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS && !itr->second.OnHold && cooldownDuration > 0 && ( spellInfo->RecoveryTime - cooldownDuration ) > (MINUTE / 2) * IN_MILLISECONDS @@ -119,11 +119,11 @@ class DuelResetScript : public PlayerScript // remove cooldowns on spells that have < 10 min CD and has no onHold player->GetSpellHistory()->ResetCooldowns([](SpellHistory::CooldownStorageType::iterator itr) -> bool { - SpellInfo const* spellInfo = sSpellMgr->EnsureSpellInfo(itr->first); - return spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS - && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first); + return spellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS + && spellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS && !itr->second.OnHold; - }, true); + }, true); } // pet cooldowns diff --git a/src/server/scripts/World/go_scripts.cpp b/src/server/scripts/World/go_scripts.cpp index b90839f50c5..3db4f41706d 100644 --- a/src/server/scripts/World/go_scripts.cpp +++ b/src/server/scripts/World/go_scripts.cpp @@ -1171,7 +1171,7 @@ public: player->CastSpell(player, SPELL_CLEANSING_SOUL); player->SetStandState(UNIT_STAND_STATE_SIT); } - return true; + return true; } }; @@ -1197,6 +1197,29 @@ public: } }; +enum MidsummerPoleRibbon +{ + SPELL_POLE_DANCE = 29726, + SPELL_BLUE_FIRE_RING = 46842, + NPC_POLE_RIBBON_BUNNY = 17066, + ACTION_COSMETIC_FIRES = 0 +}; + +class go_midsummer_ribbon_pole : public GameObjectScript +{ +public: + go_midsummer_ribbon_pole() : GameObjectScript("go_midsummer_ribbon_pole") { } + + bool OnGossipHello(Player* player, GameObject* go) override + { + if (Creature* creature = go->FindNearestCreature(NPC_POLE_RIBBON_BUNNY, 10.0f)) + { + creature->GetAI()->DoAction(ACTION_COSMETIC_FIRES); + player->CastSpell(creature, SPELL_POLE_DANCE, true); + } + return true; + } +}; enum ToyTrainSpells { @@ -1211,7 +1234,7 @@ class go_toy_train_set : public GameObjectScript struct go_toy_train_setAI : public GameObjectAI { go_toy_train_setAI(GameObject* go) : GameObjectAI(go), _pulseTimer(3 * IN_MILLISECONDS) { } - + void UpdateAI(uint32 diff) override { if (diff < _pulseTimer) @@ -1274,5 +1297,6 @@ void AddSC_go_scripts() new go_veil_skith_cage(); new go_frostblade_shrine(); new go_midsummer_bonfire(); + new go_midsummer_ribbon_pole(); new go_toy_train_set(); } diff --git a/src/server/scripts/World/item_scripts.cpp b/src/server/scripts/World/item_scripts.cpp index f4241ba0819..ff15698e579 100644 --- a/src/server/scripts/World/item_scripts.cpp +++ b/src/server/scripts/World/item_scripts.cpp @@ -57,18 +57,18 @@ public: //for special scripts switch (itemId) { - case 24538: + case 24538: if (player->GetAreaId() != 3628) disabled = true; - break; - case 34489: + break; + case 34489: if (player->GetZoneId() != 4080) disabled = true; - break; - case 34475: - if (const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(SPELL_ARCANE_CHARGES)) + break; + case 34475: + if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(SPELL_ARCANE_CHARGES)) Spell::SendCastResult(player, spellInfo, 1, SPELL_FAILED_NOT_ON_GROUND); - break; + break; } // allow use in flight only @@ -241,7 +241,7 @@ public: float x, y, z; go->GetClosePoint(x, y, z, go->GetObjectSize() / 3, 7.0f); - go->SummonGameObject(GO_HIGH_QUALITY_FUR, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), 0, 0, 0, 0, 0, 1); + go->SummonGameObject(GO_HIGH_QUALITY_FUR, *go, G3D::Quat(), 1); if (TempSummon* summon = player->SummonCreature(NPC_NESINGWARY_TRAPPER, x, y, z, go->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 1000)) { summon->SetVisible(false); diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 56d48949fac..277bc9ac804 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -36,7 +36,6 @@ npc_doctor 100% Gustaf Vanhowzen and Gregory Victor, quest 6622 npc_sayge 100% Darkmoon event fortune teller, buff player based on answers given npc_snake_trap_serpents 80% AI for snakes that summoned by Snake Trap npc_shadowfiend 100% restore 5% of owner's mana when shadowfiend die from damage -npc_locksmith 75% list of keys needs to be confirmed npc_firework 100% NPC's summoned by rockets and rocket clusters, for making them cast visual npc_train_wrecker 100% Wind-Up Train Wrecker that kills train set EndContentData */ @@ -57,7 +56,6 @@ EndContentData */ #include "SpellHistory.h" #include "SpellAuras.h" #include "Pet.h" -#include "PetAI.h" #include "CreatureTextMgr.h" #include "SmartAI.h" @@ -582,6 +580,115 @@ public: }; /*###### +## npc_midsummer_bunny_pole +######*/ + +enum RibbonPoleData +{ + GO_RIBBON_POLE = 181605, + SPELL_RIBBON_DANCE_COSMETIC = 29726, + SPELL_RED_FIRE_RING = 46836, + SPELL_BLUE_FIRE_RING = 46842, + EVENT_CAST_RED_FIRE_RING = 1, + EVENT_CAST_BLUE_FIRE_RING = 2 +}; + +class npc_midsummer_bunny_pole : public CreatureScript +{ +public: + npc_midsummer_bunny_pole() : CreatureScript("npc_midsummer_bunny_pole") { } + + struct npc_midsummer_bunny_poleAI : public ScriptedAI + { + npc_midsummer_bunny_poleAI(Creature* creature) : ScriptedAI(creature) + { + Initialize(); + } + + void Initialize() + { + events.Reset(); + running = false; + } + + void Reset() override + { + Initialize(); + } + + void DoAction(int32 /*action*/) override + { + // Don't start event if it's already running. + if (running) + return; + + running = true; + events.ScheduleEvent(EVENT_CAST_RED_FIRE_RING, 1); + } + + bool checkNearbyPlayers() + { + // Returns true if no nearby player has aura "Test Ribbon Pole Channel". + std::list<Player*> players; + Trinity::UnitAuraCheck check(true, SPELL_RIBBON_DANCE_COSMETIC); + Trinity::PlayerListSearcher<Trinity::UnitAuraCheck> searcher(me, players, check); + me->VisitNearbyWorldObject(10.0f, searcher); + + return players.empty(); + } + + void UpdateAI(uint32 diff) override + { + if (!running) + return; + + events.Update(diff); + + switch (events.ExecuteEvent()) + { + case EVENT_CAST_RED_FIRE_RING: + { + if (checkNearbyPlayers()) + { + Reset(); + return; + } + + if (GameObject* go = me->FindNearestGameObject(GO_RIBBON_POLE, 10.0f)) + me->CastSpell(go, SPELL_RED_FIRE_RING, true); + + events.ScheduleEvent(EVENT_CAST_BLUE_FIRE_RING, Seconds(5)); + } + break; + case EVENT_CAST_BLUE_FIRE_RING: + { + if (checkNearbyPlayers()) + { + Reset(); + return; + } + + if (GameObject* go = me->FindNearestGameObject(GO_RIBBON_POLE, 10.0f)) + me->CastSpell(go, SPELL_BLUE_FIRE_RING, true); + + events.ScheduleEvent(EVENT_CAST_RED_FIRE_RING, Seconds(5)); + } + break; + } + } + + private: + EventMap events; + bool running; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_midsummer_bunny_poleAI(creature); + } +}; + +/*###### ## Triage quest ######*/ @@ -1189,36 +1296,49 @@ public: enum Sayge { - SPELL_DMG = 23768, // dmg - SPELL_RES = 23769, // res - SPELL_ARM = 23767, // arm - SPELL_SPI = 23738, // spi - SPELL_INT = 23766, // int - SPELL_STM = 23737, // stm - SPELL_STR = 23735, // str - SPELL_AGI = 23736, // agi - SPELL_FORTUNE = 23765 // faire fortune + GOSSIP_MENU_OPTION_ID_ANSWER_1 = 0, + GOSSIP_MENU_OPTION_ID_ANSWER_2 = 1, + GOSSIP_MENU_OPTION_ID_ANSWER_3 = 2, + GOSSIP_MENU_OPTION_ID_ANSWER_4 = 3, + GOSSIP_I_AM_READY_TO_DISCOVER = 6186, + GOSSIP_MENU_OPTION_SAYGE1 = 6185, + GOSSIP_MENU_OPTION_SAYGE2 = 6185, + GOSSIP_MENU_OPTION_SAYGE3 = 6185, + GOSSIP_MENU_OPTION_SAYGE4 = 6185, + GOSSIP_MENU_OPTION_SAYGE5 = 6187, + GOSSIP_MENU_OPTION_SAYGE6 = 6187, + GOSSIP_MENU_OPTION_SAYGE7 = 6187, + GOSSIP_MENU_OPTION_SAYGE8 = 6208, + GOSSIP_MENU_OPTION_SAYGE9 = 6208, + GOSSIP_MENU_OPTION_SAYGE10 = 6208, + GOSSIP_MENU_OPTION_SAYGE11 = 6209, + GOSSIP_MENU_OPTION_SAYGE12 = 6209, + GOSSIP_MENU_OPTION_SAYGE13 = 6209, + GOSSIP_MENU_OPTION_SAYGE14 = 6210, + GOSSIP_MENU_OPTION_SAYGE15 = 6210, + GOSSIP_MENU_OPTION_SAYGE16 = 6210, + GOSSIP_MENU_OPTION_SAYGE17 = 6211, + GOSSIP_MENU_I_HAVE_LONG_KNOWN = 7339, + GOSSIP_MENU_YOU_HAVE_BEEN_TASKED = 7340, + GOSSIP_MENU_SWORN_EXECUTIONER = 7341, + GOSSIP_MENU_DIPLOMATIC_MISSION = 7361, + GOSSIP_MENU_YOUR_BROTHER_SEEKS = 7362, + GOSSIP_MENU_A_TERRIBLE_BEAST = 7363, + GOSSIP_MENU_YOUR_FORTUNE_IS_CAST = 7364, + GOSSIP_MENU_HERE_IS_YOUR_FORTUNE = 7365, + GOSSIP_MENU_CANT_GIVE_YOU_YOUR = 7393, + + SPELL_STRENGTH = 23735, // +10% Strength + SPELL_AGILITY = 23736, // +10% Agility + SPELL_STAMINA = 23737, // +10% Stamina + SPELL_SPIRIT = 23738, // +10% Spirit + SPELL_INTELLECT = 23766, // +10% Intellect + SPELL_ARMOR = 23767, // +10% Armor + SPELL_DAMAGE = 23768, // +10% Damage + SPELL_RESISTANCE = 23769, // +25 Magic Resistance (All) + SPELL_FORTUNE = 23765 // Darkmoon Faire Fortune }; -#define GOSSIP_HELLO_SAYGE "Yes" -#define GOSSIP_SENDACTION_SAYGE1 "Slay the Man" -#define GOSSIP_SENDACTION_SAYGE2 "Turn him over to liege" -#define GOSSIP_SENDACTION_SAYGE3 "Confiscate the corn" -#define GOSSIP_SENDACTION_SAYGE4 "Let him go and have the corn" -#define GOSSIP_SENDACTION_SAYGE5 "Execute your friend painfully" -#define GOSSIP_SENDACTION_SAYGE6 "Execute your friend painlessly" -#define GOSSIP_SENDACTION_SAYGE7 "Let your friend go" -#define GOSSIP_SENDACTION_SAYGE8 "Confront the diplomat" -#define GOSSIP_SENDACTION_SAYGE9 "Show not so quiet defiance" -#define GOSSIP_SENDACTION_SAYGE10 "Remain quiet" -#define GOSSIP_SENDACTION_SAYGE11 "Speak against your brother openly" -#define GOSSIP_SENDACTION_SAYGE12 "Help your brother in" -#define GOSSIP_SENDACTION_SAYGE13 "Keep your brother out without letting him know" -#define GOSSIP_SENDACTION_SAYGE14 "Take credit, keep gold" -#define GOSSIP_SENDACTION_SAYGE15 "Take credit, share the gold" -#define GOSSIP_SENDACTION_SAYGE16 "Let the knight take credit" -#define GOSSIP_SENDACTION_SAYGE17 "Thanks" - class npc_sayge : public CreatureScript { public: @@ -1229,19 +1349,19 @@ public: if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); - if (player->GetSpellHistory()->HasCooldown(SPELL_INT) || - player->GetSpellHistory()->HasCooldown(SPELL_ARM) || - player->GetSpellHistory()->HasCooldown(SPELL_DMG) || - player->GetSpellHistory()->HasCooldown(SPELL_RES) || - player->GetSpellHistory()->HasCooldown(SPELL_STR) || - player->GetSpellHistory()->HasCooldown(SPELL_AGI) || - player->GetSpellHistory()->HasCooldown(SPELL_STM) || - player->GetSpellHistory()->HasCooldown(SPELL_SPI)) - player->SEND_GOSSIP_MENU(7393, creature->GetGUID()); + if (player->GetSpellHistory()->HasCooldown(SPELL_STRENGTH) || + player->GetSpellHistory()->HasCooldown(SPELL_AGILITY) || + player->GetSpellHistory()->HasCooldown(SPELL_STAMINA) || + player->GetSpellHistory()->HasCooldown(SPELL_SPIRIT) || + player->GetSpellHistory()->HasCooldown(SPELL_INTELLECT) || + player->GetSpellHistory()->HasCooldown(SPELL_ARMOR) || + player->GetSpellHistory()->HasCooldown(SPELL_DAMAGE) || + player->GetSpellHistory()->HasCooldown(SPELL_RESISTANCE)) + player->SEND_GOSSIP_MENU(GOSSIP_MENU_CANT_GIVE_YOU_YOUR, creature->GetGUID()); else { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_SAYGE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - player->SEND_GOSSIP_MENU(7339, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_I_AM_READY_TO_DISCOVER, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_I_HAVE_LONG_KNOWN, creature->GetGUID()); } return true; @@ -1252,43 +1372,43 @@ public: switch (action) { case GOSSIP_ACTION_INFO_DEF + 1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); - player->SEND_GOSSIP_MENU(7340, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE1, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE2, GOSSIP_MENU_OPTION_ID_ANSWER_2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE3, GOSSIP_MENU_OPTION_ID_ANSWER_3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE4, GOSSIP_MENU_OPTION_ID_ANSWER_4, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_YOU_HAVE_BEEN_TASKED, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF + 2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE5, GOSSIP_SENDER_MAIN + 1, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE6, GOSSIP_SENDER_MAIN + 2, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE7, GOSSIP_SENDER_MAIN + 3, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(7341, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE5, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN + 1, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE6, GOSSIP_MENU_OPTION_ID_ANSWER_2, GOSSIP_SENDER_MAIN + 2, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE7, GOSSIP_MENU_OPTION_ID_ANSWER_3, GOSSIP_SENDER_MAIN + 3, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_SWORN_EXECUTIONER, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF + 3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE8, GOSSIP_SENDER_MAIN + 4, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE9, GOSSIP_SENDER_MAIN + 5, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE10, GOSSIP_SENDER_MAIN + 2, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(7361, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE8, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN + 4, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE9, GOSSIP_MENU_OPTION_ID_ANSWER_2, GOSSIP_SENDER_MAIN + 5, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE10,GOSSIP_MENU_OPTION_ID_ANSWER_3, GOSSIP_SENDER_MAIN + 2, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_DIPLOMATIC_MISSION, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF + 4: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE11, GOSSIP_SENDER_MAIN + 6, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE12, GOSSIP_SENDER_MAIN + 7, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE13, GOSSIP_SENDER_MAIN + 8, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(7362, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE11, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN + 6, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE12, GOSSIP_MENU_OPTION_ID_ANSWER_2, GOSSIP_SENDER_MAIN + 7, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE13, GOSSIP_MENU_OPTION_ID_ANSWER_3, GOSSIP_SENDER_MAIN + 8, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_YOUR_BROTHER_SEEKS, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF + 5: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE14, GOSSIP_SENDER_MAIN + 5, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE15, GOSSIP_SENDER_MAIN + 4, GOSSIP_ACTION_INFO_DEF); - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE16, GOSSIP_SENDER_MAIN + 3, GOSSIP_ACTION_INFO_DEF); - player->SEND_GOSSIP_MENU(7363, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE14, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN + 5, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE15, GOSSIP_MENU_OPTION_ID_ANSWER_2, GOSSIP_SENDER_MAIN + 4, GOSSIP_ACTION_INFO_DEF); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE16, GOSSIP_MENU_OPTION_ID_ANSWER_3, GOSSIP_SENDER_MAIN + 3, GOSSIP_ACTION_INFO_DEF); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_A_TERRIBLE_BEAST, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SENDACTION_SAYGE17, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); - player->SEND_GOSSIP_MENU(7364, creature->GetGUID()); + player->ADD_GOSSIP_ITEM_DB(GOSSIP_MENU_OPTION_SAYGE17, GOSSIP_MENU_OPTION_ID_ANSWER_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_YOUR_FORTUNE_IS_CAST, creature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF + 6: creature->CastSpell(player, SPELL_FORTUNE, false); - player->SEND_GOSSIP_MENU(7365, creature->GetGUID()); + player->SEND_GOSSIP_MENU(GOSSIP_MENU_HERE_IS_YOUR_FORTUNE, creature->GetGUID()); break; } } @@ -1303,28 +1423,28 @@ public: SendAction(player, creature, action); break; case GOSSIP_SENDER_MAIN + 1: - spellId = SPELL_DMG; + spellId = SPELL_DAMAGE; break; case GOSSIP_SENDER_MAIN + 2: - spellId = SPELL_RES; + spellId = SPELL_RESISTANCE; break; case GOSSIP_SENDER_MAIN + 3: - spellId = SPELL_ARM; + spellId = SPELL_ARMOR; break; case GOSSIP_SENDER_MAIN + 4: - spellId = SPELL_SPI; + spellId = SPELL_SPIRIT; break; case GOSSIP_SENDER_MAIN + 5: - spellId = SPELL_INT; + spellId = SPELL_INTELLECT; break; case GOSSIP_SENDER_MAIN + 6: - spellId = SPELL_STM; + spellId = SPELL_STAMINA; break; case GOSSIP_SENDER_MAIN + 7: - spellId = SPELL_STR; + spellId = SPELL_STRENGTH; break; case GOSSIP_SENDER_MAIN + 8: - spellId = SPELL_AGI; + spellId = SPELL_AGILITY; break; } @@ -1744,149 +1864,6 @@ public: }; /*###### -## npc_locksmith -######*/ - -enum LockSmith -{ - QUEST_HOW_TO_BRAKE_IN_TO_THE_ARCATRAZ = 10704, - QUEST_DARK_IRON_LEGACY = 3802, - QUEST_THE_KEY_TO_SCHOLOMANCE_A = 5505, - QUEST_THE_KEY_TO_SCHOLOMANCE_H = 5511, - QUEST_HOTTER_THAN_HELL_A = 10758, - QUEST_HOTTER_THAN_HELL_H = 10764, - QUEST_RETURN_TO_KHAGDAR = 9837, - QUEST_CONTAINMENT = 13159, - QUEST_ETERNAL_VIGILANCE = 11011, - QUEST_KEY_TO_THE_FOCUSING_IRIS = 13372, - QUEST_HC_KEY_TO_THE_FOCUSING_IRIS = 13375, - - ITEM_ARCATRAZ_KEY = 31084, - ITEM_SHADOWFORGE_KEY = 11000, - ITEM_SKELETON_KEY = 13704, - ITEM_SHATTERED_HALLS_KEY = 28395, - ITEM_THE_MASTERS_KEY = 24490, - ITEM_VIOLET_HOLD_KEY = 42482, - ITEM_ESSENCE_INFUSED_MOONSTONE = 32449, - ITEM_KEY_TO_THE_FOCUSING_IRIS = 44582, - ITEM_HC_KEY_TO_THE_FOCUSING_IRIS = 44581, - - SPELL_ARCATRAZ_KEY = 54881, - SPELL_SHADOWFORGE_KEY = 54882, - SPELL_SKELETON_KEY = 54883, - SPELL_SHATTERED_HALLS_KEY = 54884, - SPELL_THE_MASTERS_KEY = 54885, - SPELL_VIOLET_HOLD_KEY = 67253, - SPELL_ESSENCE_INFUSED_MOONSTONE = 40173, -}; - -#define GOSSIP_LOST_ARCATRAZ_KEY "I've lost my key to the Arcatraz." -#define GOSSIP_LOST_SHADOWFORGE_KEY "I've lost my key to the Blackrock Depths." -#define GOSSIP_LOST_SKELETON_KEY "I've lost my key to the Scholomance." -#define GOSSIP_LOST_SHATTERED_HALLS_KEY "I've lost my key to the Shattered Halls." -#define GOSSIP_LOST_THE_MASTERS_KEY "I've lost my key to the Karazhan." -#define GOSSIP_LOST_VIOLET_HOLD_KEY "I've lost my key to the Violet Hold." -#define GOSSIP_LOST_ESSENCE_INFUSED_MOONSTONE "I've lost my Essence-Infused Moonstone." -#define GOSSIP_LOST_KEY_TO_THE_FOCUSING_IRIS "I've lost my Key to the Focusing Iris." -#define GOSSIP_LOST_HC_KEY_TO_THE_FOCUSING_IRIS "I've lost my Heroic Key to the Focusing Iris." - -class npc_locksmith : public CreatureScript -{ -public: - npc_locksmith() : CreatureScript("npc_locksmith") { } - - bool OnGossipHello(Player* player, Creature* creature) override - { - // Arcatraz Key - if (player->GetQuestRewardStatus(QUEST_HOW_TO_BRAKE_IN_TO_THE_ARCATRAZ) && !player->HasItemCount(ITEM_ARCATRAZ_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_ARCATRAZ_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - - // Shadowforge Key - if (player->GetQuestRewardStatus(QUEST_DARK_IRON_LEGACY) && !player->HasItemCount(ITEM_SHADOWFORGE_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_SHADOWFORGE_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 2); - - // Skeleton Key - if ((player->GetQuestRewardStatus(QUEST_THE_KEY_TO_SCHOLOMANCE_A) || player->GetQuestRewardStatus(QUEST_THE_KEY_TO_SCHOLOMANCE_H)) && - !player->HasItemCount(ITEM_SKELETON_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_SKELETON_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 3); - - // Shatered Halls Key - if ((player->GetQuestRewardStatus(QUEST_HOTTER_THAN_HELL_A) || player->GetQuestRewardStatus(QUEST_HOTTER_THAN_HELL_H)) && - !player->HasItemCount(ITEM_SHATTERED_HALLS_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_SHATTERED_HALLS_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 4); - - // Master's Key - if (player->GetQuestRewardStatus(QUEST_RETURN_TO_KHAGDAR) && !player->HasItemCount(ITEM_THE_MASTERS_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_THE_MASTERS_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 5); - - // Violet Hold Key - if (player->GetQuestRewardStatus(QUEST_CONTAINMENT) && !player->HasItemCount(ITEM_VIOLET_HOLD_KEY, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_VIOLET_HOLD_KEY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 6); - - // Essence-Infused Moonstone - if (player->GetQuestRewardStatus(QUEST_ETERNAL_VIGILANCE) && !player->HasItemCount(ITEM_ESSENCE_INFUSED_MOONSTONE, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_ESSENCE_INFUSED_MOONSTONE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 7); - - // Key to the Focusing Iris - if (player->GetQuestRewardStatus(QUEST_KEY_TO_THE_FOCUSING_IRIS) && !player->HasItemCount(ITEM_KEY_TO_THE_FOCUSING_IRIS, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_KEY_TO_THE_FOCUSING_IRIS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 8); - - // Heroic Key to the Focusing Iris - if (player->GetQuestRewardStatus(QUEST_HC_KEY_TO_THE_FOCUSING_IRIS) && !player->HasItemCount(ITEM_HC_KEY_TO_THE_FOCUSING_IRIS, 1, true)) - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOST_HC_KEY_TO_THE_FOCUSING_IRIS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 9); - - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - - return true; - } - - bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) override - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF + 1: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_ARCATRAZ_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 2: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_SHADOWFORGE_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 3: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_SKELETON_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 4: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_SHATTERED_HALLS_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 5: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_THE_MASTERS_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 6: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_VIOLET_HOLD_KEY, false); - break; - case GOSSIP_ACTION_INFO_DEF + 7: - player->CLOSE_GOSSIP_MENU(); - player->CastSpell(player, SPELL_ESSENCE_INFUSED_MOONSTONE, false); - break; - case GOSSIP_ACTION_INFO_DEF + 8: - player->CLOSE_GOSSIP_MENU(); - player->AddItem(ITEM_KEY_TO_THE_FOCUSING_IRIS, 1); - break; - case GOSSIP_ACTION_INFO_DEF + 9: - player->CLOSE_GOSSIP_MENU(); - player->AddItem(ITEM_HC_KEY_TO_THE_FOCUSING_IRIS, 1); - break; - } - return true; - } -}; - -/*###### ## npc_experience ######*/ @@ -2192,7 +2169,7 @@ public: // Check if we are near Elune'ara lake south, if so try to summon Omen or a minion if (me->GetZoneId() == ZONE_MOONGLADE) { - if (!me->FindNearestCreature(NPC_OMEN, 100.0f, false) && me->GetDistance2d(omenSummonPos.GetPositionX(), omenSummonPos.GetPositionY()) <= 100.0f) + if (!me->FindNearestCreature(NPC_OMEN, 100.0f) && me->GetDistance2d(omenSummonPos.GetPositionX(), omenSummonPos.GetPositionY()) <= 100.0f) { switch (urand(0, 9)) { @@ -2214,7 +2191,7 @@ public: float displacement = 0.7f; for (uint8 i = 0; i < 4; i++) - me->SummonGameObject(GetFireworkGameObjectId(), me->GetPositionX() + (i%2 == 0 ? displacement : -displacement), me->GetPositionY() + (i > 1 ? displacement : -displacement), me->GetPositionZ() + 4.0f, me->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 1); + me->SummonGameObject(GetFireworkGameObjectId(), me->GetPositionX() + (i % 2 == 0 ? displacement : -displacement), me->GetPositionY() + (i > 1 ? displacement : -displacement), me->GetPositionZ() + 4.0f, me->GetOrientation(), G3D::Quat(), 1); } else //me->CastSpell(me, GetFireworkSpell(me->GetEntry()), true); @@ -2572,159 +2549,6 @@ class npc_train_wrecker : public CreatureScript } }; -enum EgbertMisc -{ - EVENT_MOVE_POS = 1, - EVENT_RETURN = 2 -}; - -class npc_egbert : public CreatureScript -{ -public: - npc_egbert() : CreatureScript("npc_egbert") {} - - struct npc_egbertAI : public PetAI - { - npc_egbertAI(Creature* creature) : PetAI(creature) - { - if (Unit* owner = me->GetCharmerOrOwner()) - if (owner->GetMap()->GetEntry()->addon > 1) - me->SetCanFly(true); - } - - void Reset() override - { - _events.Reset(); - _events.ScheduleEvent(EVENT_MOVE_POS, urandms(1, 20)); - } - - void UpdateAI(uint32 diff) override - { - _events.Update(diff); - - while (uint32 eventId = _events.ExecuteEvent()) - { - switch (eventId) - { - case EVENT_MOVE_POS: - if (Unit* owner = me->GetCharmerOrOwner()) - { - me->GetMotionMaster()->Clear(); - me->GetMotionMaster()->MovePoint(0, owner->GetPositionX() + frand(-30.0f, 30.0f), owner->GetPositionY() + frand(-30.0f, 30.0f), owner->GetPositionZ()); - } - _events.ScheduleEvent(EVENT_RETURN, urandms(3, 4)); - break; - case EVENT_RETURN: - if (Unit* owner = me->GetCharmerOrOwner()) - me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, me->GetFollowAngle()); - _events.ScheduleEvent(EVENT_MOVE_POS, urandms(1, 20)); - break; - default: - break; - } - } - } - private: - EventMap _events; - }; - - CreatureAI* GetAI(Creature* creature) const - { - return new npc_egbertAI(creature); - } -}; - -enum PandarenMonkMisc -{ - SPELL_PANDAREN_MONK = 69800, - EVENT_FOCUS = 1, - EVENT_EMOTE = 2, - EVENT_FOLLOW = 3, - EVENT_DRINK = 4 -}; - -class npc_pandaren_monk : public CreatureScript -{ -public: - npc_pandaren_monk() : CreatureScript("npc_pandaren_monk") {} - - struct npc_pandaren_monkAI : public NullCreatureAI - { - npc_pandaren_monkAI(Creature* creature) : NullCreatureAI(creature) { } - - void Reset() override - { - _events.Reset(); - _events.ScheduleEvent(EVENT_FOCUS, 1000); - } - - void EnterEvadeMode(EvadeReason why) override - { - if (!_EnterEvadeMode(why)) - return; - - Reset(); - } - - void ReceiveEmote(Player* /*player*/, uint32 emote) override - { - me->InterruptSpell(CURRENT_CHANNELED_SPELL); - me->StopMoving(); - - switch (emote) - { - case TEXT_EMOTE_BOW: - _events.ScheduleEvent(EVENT_FOCUS, 1000); - break; - case TEXT_EMOTE_DRINK: - _events.ScheduleEvent(EVENT_DRINK, 1000); - break; - } - } - - void UpdateAI(uint32 diff) override - { - _events.Update(diff); - - if (Unit* owner = me->GetCharmerOrOwner()) - if (!me->IsWithinDist(owner, 30.f)) - me->InterruptSpell(CURRENT_CHANNELED_SPELL); - - while (uint32 eventId = _events.ExecuteEvent()) - { - switch (eventId) - { - case EVENT_FOCUS: - if (Unit* owner = me->GetCharmerOrOwner()) - me->SetFacingToObject(owner); - _events.ScheduleEvent(EVENT_EMOTE, 1000); - break; - case EVENT_EMOTE: - me->HandleEmoteCommand(EMOTE_ONESHOT_BOW); - _events.ScheduleEvent(EVENT_FOLLOW, 1000); - break; - case EVENT_FOLLOW: - if (Unit* owner = me->GetCharmerOrOwner()) - me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); - break; - case EVENT_DRINK: - me->CastSpell(me, SPELL_PANDAREN_MONK, false); - break; - default: - break; - } - } - } - private: - EventMap _events; - }; - - CreatureAI* GetAI(Creature* creature) const - { - return new npc_pandaren_monkAI(creature); - } -}; - void AddSC_npcs_special() { new npc_air_force_bots(); @@ -2732,6 +2556,7 @@ void AddSC_npcs_special() new npc_chicken_cluck(); new npc_dancing_flames(); new npc_torch_tossing_target_bunny_controller(); + new npc_midsummer_bunny_pole(); new npc_doctor(); new npc_injured_patient(); new npc_garments_of_quests(); @@ -2743,13 +2568,10 @@ void AddSC_npcs_special() new npc_training_dummy(); new npc_wormhole(); new npc_pet_trainer(); - new npc_locksmith(); new npc_experience(); new npc_firework(); new npc_spring_rabbit(); new npc_imp_in_a_ball(); new npc_stable_master(); new npc_train_wrecker(); - new npc_egbert(); - new npc_pandaren_monk(); } diff --git a/src/server/scripts/World/world_script_loader.cpp b/src/server/scripts/World/world_script_loader.cpp new file mode 100644 index 00000000000..0167024799f --- /dev/null +++ b/src/server/scripts/World/world_script_loader.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "World.h" + +// This is where scripts' loading functions should be declared: +// world +void AddSC_areatrigger_scripts(); +void AddSC_emerald_dragons(); +void AddSC_generic_creature(); +void AddSC_go_scripts(); +void AddSC_guards(); +void AddSC_item_scripts(); +void AddSC_npc_professions(); +void AddSC_npc_innkeeper(); +void AddSC_npcs_special(); +void AddSC_achievement_scripts(); +void AddSC_action_ip_logger(); +void AddSC_duel_reset(); +// player +void AddSC_chat_log(); +void AddSC_action_ip_logger(); + +// The name of this function should match: +// void Add${NameOfDirectory}Scripts() +void AddWorldScripts() +{ + AddSC_areatrigger_scripts(); + AddSC_emerald_dragons(); + AddSC_generic_creature(); + AddSC_go_scripts(); + AddSC_guards(); + AddSC_item_scripts(); + AddSC_npc_professions(); + AddSC_npc_innkeeper(); + AddSC_npcs_special(); + AddSC_achievement_scripts(); + AddSC_chat_log(); // location: scripts\World\chat_log.cpp + + // FIXME: This should be moved in a script validation hook. + // To avoid duplicate code, we check once /*ONLY*/ if logging is permitted or not. + if (sWorld->getBoolConfig(CONFIG_IP_BASED_ACTION_LOGGING)) + AddSC_action_ip_logger(); // location: scripts\World\action_ip_logger.cpp + AddSC_duel_reset(); +} diff --git a/src/server/shared/CMakeLists.txt b/src/server/shared/CMakeLists.txt index b6e5c8b1c6f..e99a81a084b 100644 --- a/src/server/shared/CMakeLists.txt +++ b/src/server/shared/CMakeLists.txt @@ -8,62 +8,60 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -if( USE_COREPCH ) - include_directories(${CMAKE_CURRENT_BINARY_DIR}) -endif() - -file(GLOB_RECURSE sources_DataStores DataStores/*.cpp DataStores/*.h) -file(GLOB_RECURSE sources_Dynamic Dynamic/*.cpp Dynamic/*.h) -file(GLOB_RECURSE sources_Networking Networking/*.cpp Networking/*.h) -file(GLOB_RECURSE sources_Packets Packets/*.cpp Packets/*.h) -if( WIN32 ) - file(GLOB_RECURSE sources_Service Service/*.cpp Service/*.h) -endif( WIN32 ) -file(GLOB sources_localdir *.cpp *.h) - -# -# Build shared sourcelist -# +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) if (USE_COREPCH) - set(shared_STAT_PCH_HDR PrecompiledHeaders/sharedPCH.h) - set(shared_STAT_PCH_SRC PrecompiledHeaders/sharedPCH.cpp) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/sharedPCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/sharedPCH.cpp) endif() -set(shared_STAT_SRCS - ${shared_STAT_SRCS} - ${sources_DataStores} - ${sources_Dynamic} - ${sources_Networking} - ${sources_Packets} - ${sources_Utilities} - ${sources_Service} - ${sources_localdir} -) +GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/Dynamic - ${CMAKE_CURRENT_SOURCE_DIR}/Networking - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/src/common/ - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${MYSQL_INCLUDE_DIR} - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} +add_definitions(-DTRINITY_API_EXPORT_SHARED) + +add_library(shared + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES} ) -GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) -add_library(shared STATIC - ${shared_STAT_SRCS} - ${shared_STAT_PCH_SRC} -) +target_include_directories(shared + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) -add_dependencies(shared revision_data.h) +target_link_libraries(shared + PUBLIC + database) + +set_target_properties(shared + PROPERTIES + FOLDER + "server") + +if( BUILD_SHARED_LIBS ) + if( UNIX ) + install(TARGETS shared + LIBRARY + DESTINATION lib) + elseif( WIN32 ) + install(TARGETS shared + RUNTIME + DESTINATION "${CMAKE_INSTALL_PREFIX}") + endif() +endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(shared ${shared_STAT_PCH_HDR} ${shared_STAT_PCH_SRC}) + add_cxx_pch(shared ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif () diff --git a/src/server/shared/DataStores/DBCFileLoader.h b/src/server/shared/DataStores/DBCFileLoader.h index 00b1ee54a4a..abe18d1425e 100644 --- a/src/server/shared/DataStores/DBCFileLoader.h +++ b/src/server/shared/DataStores/DBCFileLoader.h @@ -37,7 +37,7 @@ enum DbcFieldFormat FT_SQL_ABSENT='a' //Used in sql format to mark column absent in sql dbc }; -class DBCFileLoader +class TC_SHARED_API DBCFileLoader { public: DBCFileLoader(); diff --git a/src/server/shared/Networking/AsyncAcceptor.h b/src/server/shared/Networking/AsyncAcceptor.h index 260e1c8ea11..f68da230553 100644 --- a/src/server/shared/Networking/AsyncAcceptor.h +++ b/src/server/shared/Networking/AsyncAcceptor.h @@ -20,34 +20,40 @@ #include "Log.h" #include <boost/asio.hpp> +#include <functional> +#include <atomic> using boost::asio::ip::tcp; class AsyncAcceptor { public: - typedef void(*ManagerAcceptHandler)(tcp::socket&& newSocket); + typedef void(*AcceptCallback)(tcp::socket&& newSocket, uint32 threadIndex); AsyncAcceptor(boost::asio::io_service& ioService, std::string const& bindIp, uint16 port) : _acceptor(ioService, tcp::endpoint(boost::asio::ip::address::from_string(bindIp), port)), - _socket(ioService) + _socket(ioService), _closed(false), _socketFactory(std::bind(&AsyncAcceptor::DefeaultSocketFactory, this)) { } - template <class T> + template<class T> void AsyncAccept(); - void AsyncAcceptManaged(ManagerAcceptHandler mgrHandler) + template<AcceptCallback acceptCallback> + void AsyncAcceptWithCallback() { - _acceptor.async_accept(_socket, [this, mgrHandler](boost::system::error_code error) + tcp::socket* socket; + uint32 threadIndex; + std::tie(socket, threadIndex) = _socketFactory(); + _acceptor.async_accept(*socket, [this, socket, threadIndex](boost::system::error_code error) { if (!error) { try { - _socket.non_blocking(true); + socket->non_blocking(true); - mgrHandler(std::move(_socket)); + acceptCallback(std::move(*socket), threadIndex); } catch (boost::system::system_error const& err) { @@ -55,13 +61,29 @@ public: } } - AsyncAcceptManaged(mgrHandler); + if (!_closed) + this->AsyncAcceptWithCallback<acceptCallback>(); }); } + void Close() + { + if (_closed.exchange(true)) + return; + + boost::system::error_code err; + _acceptor.close(err); + } + + void SetSocketFactory(std::function<std::pair<tcp::socket*, uint32>()> func) { _socketFactory = func; } + private: + std::pair<tcp::socket*, uint32> DefeaultSocketFactory() { return std::make_pair(&_socket, 0); } + tcp::acceptor _acceptor; tcp::socket _socket; + std::atomic<bool> _closed; + std::function<std::pair<tcp::socket*, uint32>()> _socketFactory; }; template<class T> @@ -83,7 +105,8 @@ void AsyncAcceptor::AsyncAccept() } // lets slap some more this-> on this so we can fix this bug with gcc 4.7.2 throwing internals in yo face - this->AsyncAccept<T>(); + if (!_closed) + this->AsyncAccept<T>(); }); } diff --git a/src/server/shared/Networking/NetworkThread.h b/src/server/shared/Networking/NetworkThread.h index ac216838bce..be0e9f10176 100644 --- a/src/server/shared/Networking/NetworkThread.h +++ b/src/server/shared/Networking/NetworkThread.h @@ -22,6 +22,8 @@ #include "Errors.h" #include "Log.h" #include "Timer.h" +#include <boost/asio/ip/tcp.hpp> +#include <boost/asio/deadline_timer.hpp> #include <atomic> #include <chrono> #include <memory> @@ -29,11 +31,14 @@ #include <set> #include <thread> +using boost::asio::ip::tcp; + template<class SocketType> class NetworkThread { public: - NetworkThread() : _connections(0), _stopped(false), _thread(nullptr) + NetworkThread() : _connections(0), _stopped(false), _thread(nullptr), + _acceptSocket(_io_service), _updateTimer(_io_service) { } @@ -50,6 +55,7 @@ public: void Stop() { _stopped = true; + _io_service.stop(); } bool Start() @@ -80,10 +86,12 @@ public: std::lock_guard<std::mutex> lock(_newSocketsLock); ++_connections; - _newSockets.insert(sock); + _newSockets.push_back(sock); SocketAdded(sock); } + tcp::socket* GetSocketForAccept() { return &_acceptSocket; } + protected: virtual void SocketAdded(std::shared_ptr<SocketType> /*sock*/) { } virtual void SocketRemoved(std::shared_ptr<SocketType> /*sock*/) { } @@ -95,16 +103,15 @@ protected: if (_newSockets.empty()) return; - for (typename SocketSet::const_iterator i = _newSockets.begin(); i != _newSockets.end(); ++i) + for (std::shared_ptr<SocketType> sock : _newSockets) { - if (!(*i)->IsOpen()) + if (!sock->IsOpen()) { - SocketRemoved(*i); - + SocketRemoved(sock); --_connections; } else - _Sockets.insert(*i); + _sockets.push_back(sock); } _newSockets.clear(); @@ -114,53 +121,58 @@ protected: { TC_LOG_DEBUG("misc", "Network Thread Starting"); - typename SocketSet::iterator i, t; + _updateTimer.expires_from_now(boost::posix_time::milliseconds(10)); + _updateTimer.async_wait(std::bind(&NetworkThread<SocketType>::Update, this)); + _io_service.run(); - uint32 sleepTime = 10; - uint32 tickStart = 0, diff = 0; - while (!_stopped) - { - std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); + TC_LOG_DEBUG("misc", "Network Thread exits"); + _newSockets.clear(); + _sockets.clear(); + } + + void Update() + { + if (_stopped) + return; - tickStart = getMSTime(); + _updateTimer.expires_from_now(boost::posix_time::milliseconds(10)); + _updateTimer.async_wait(std::bind(&NetworkThread<SocketType>::Update, this)); - AddNewSockets(); + AddNewSockets(); - for (i = _Sockets.begin(); i != _Sockets.end();) + _sockets.erase(std::remove_if(_sockets.begin(), _sockets.end(), [this](std::shared_ptr<SocketType> sock) + { + if (!sock->Update()) { - if (!(*i)->Update()) - { - if ((*i)->IsOpen()) - (*i)->CloseSocket(); - - SocketRemoved(*i); - - --_connections; - _Sockets.erase(i++); - } - else - ++i; - } + if (sock->IsOpen()) + sock->CloseSocket(); - diff = GetMSTimeDiffToNow(tickStart); - sleepTime = diff > 10 ? 0 : 10 - diff; - } + this->SocketRemoved(sock); - TC_LOG_DEBUG("misc", "Network Thread exits"); + --this->_connections; + return true; + } + + return false; + }), _sockets.end()); } private: - typedef std::set<std::shared_ptr<SocketType> > SocketSet; + typedef std::vector<std::shared_ptr<SocketType>> SocketContainer; std::atomic<int32> _connections; std::atomic<bool> _stopped; std::thread* _thread; - SocketSet _Sockets; + SocketContainer _sockets; std::mutex _newSocketsLock; - SocketSet _newSockets; + SocketContainer _newSockets; + + boost::asio::io_service _io_service; + tcp::socket _acceptSocket; + boost::asio::deadline_timer _updateTimer; }; #endif // NetworkThread_h__ diff --git a/src/server/shared/Networking/Socket.h b/src/server/shared/Networking/Socket.h index a2f57b5029e..0674ede57d8 100644 --- a/src/server/shared/Networking/Socket.h +++ b/src/server/shared/Networking/Socket.h @@ -21,15 +21,11 @@ #include "MessageBuffer.h" #include "Log.h" #include <atomic> -#include <vector> -#include <mutex> #include <queue> #include <memory> #include <functional> #include <type_traits> #include <boost/asio/ip/tcp.hpp> -#include <boost/asio/write.hpp> -#include <boost/asio/read.hpp> using boost::asio::ip::tcp; @@ -59,18 +55,14 @@ public: virtual bool Update() { - if (!IsOpen()) + if (_closed) return false; #ifndef TC_SOCKET_USE_IOCP - std::unique_lock<std::mutex> guard(_writeLock); - if (!guard) - return true; - - if (_isWritingAsync || (!_writeBuffer.GetActiveSize() && _writeQueue.empty())) + if (_isWritingAsync || (_writeQueue.empty() && !_closing)) return true; - for (; WriteHandler(guard);) + for (; HandleQueue();) ; #endif @@ -98,14 +90,23 @@ public: std::bind(&Socket<T>::ReadHandlerInternal, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } - void QueuePacket(MessageBuffer&& buffer, std::unique_lock<std::mutex>& guard) + void AsyncReadWithCallback(void (T::*callback)(boost::system::error_code, std::size_t)) + { + if (!IsOpen()) + return; + + _readBuffer.Normalize(); + _readBuffer.EnsureFreeSpace(); + _socket.async_read_some(boost::asio::buffer(_readBuffer.GetWritePointer(), _readBuffer.GetRemainingSpace()), + std::bind(callback, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2)); + } + + void QueuePacket(MessageBuffer&& buffer) { _writeQueue.push(std::move(buffer)); #ifdef TC_SOCKET_USE_IOCP - AsyncProcessQueue(guard); -#else - (void)guard; + AsyncProcessQueue(); #endif } @@ -135,7 +136,7 @@ protected: virtual void ReadHandler() = 0; - bool AsyncProcessQueue(std::unique_lock<std::mutex>&) + bool AsyncProcessQueue() { if (_isWritingAsync) return false; @@ -154,13 +155,14 @@ protected: return false; } - std::mutex _writeLock; - std::queue<MessageBuffer> _writeQueue; -#ifndef TC_SOCKET_USE_IOCP - MessageBuffer _writeBuffer; -#endif - - boost::asio::io_service& io_service() { return _socket.get_io_service(); } + void SetNoDelay(bool enable) + { + boost::system::error_code err; + _socket.set_option(tcp::no_delay(enable), err); + if (err) + TC_LOG_DEBUG("network", "Socket::SetNoDelay: failed to set_option(boost::asio::ip::tcp::no_delay) for %s - %d (%s)", + GetRemoteIpAddress().to_string().c_str(), err.value(), err.message().c_str()); + } private: void ReadHandlerInternal(boost::system::error_code error, size_t transferredBytes) @@ -181,15 +183,13 @@ private: { if (!error) { - std::unique_lock<std::mutex> deleteGuard(_writeLock); - _isWritingAsync = false; _writeQueue.front().ReadCompleted(transferedBytes); if (!_writeQueue.front().GetActiveSize()) _writeQueue.pop(); if (!_writeQueue.empty()) - AsyncProcessQueue(deleteGuard); + AsyncProcessQueue(); else if (_closing) CloseSocket(); } @@ -201,47 +201,11 @@ private: void WriteHandlerWrapper(boost::system::error_code /*error*/, std::size_t /*transferedBytes*/) { - std::unique_lock<std::mutex> guard(_writeLock); _isWritingAsync = false; - WriteHandler(guard); + HandleQueue(); } - bool WriteHandler(std::unique_lock<std::mutex>& guard) - { - if (!IsOpen()) - return false; - - std::size_t bytesToSend = _writeBuffer.GetActiveSize(); - - if (bytesToSend == 0) - return HandleQueue(guard); - - boost::system::error_code error; - std::size_t bytesWritten = _socket.write_some(boost::asio::buffer(_writeBuffer.GetReadPointer(), bytesToSend), error); - - if (error) - { - if (error == boost::asio::error::would_block || error == boost::asio::error::try_again) - return AsyncProcessQueue(guard); - - return false; - } - else if (bytesWritten == 0) - return false; - else if (bytesWritten < bytesToSend) - { - _writeBuffer.ReadCompleted(bytesWritten); - _writeBuffer.Normalize(); - return AsyncProcessQueue(guard); - } - - // now bytesWritten == bytesToSend - _writeBuffer.Reset(); - - return HandleQueue(guard); - } - - bool HandleQueue(std::unique_lock<std::mutex>& guard) + bool HandleQueue() { if (_writeQueue.empty()) return false; @@ -256,23 +220,29 @@ private: if (error) { if (error == boost::asio::error::would_block || error == boost::asio::error::try_again) - return AsyncProcessQueue(guard); + return AsyncProcessQueue(); _writeQueue.pop(); + if (_closing && _writeQueue.empty()) + CloseSocket(); return false; } else if (bytesSent == 0) { _writeQueue.pop(); + if (_closing && _writeQueue.empty()) + CloseSocket(); return false; } else if (bytesSent < bytesToSend) // now n > 0 { queuedMessage.ReadCompleted(bytesSent); - return AsyncProcessQueue(guard); + return AsyncProcessQueue(); } _writeQueue.pop(); + if (_closing && _writeQueue.empty()) + CloseSocket(); return !_writeQueue.empty(); } @@ -284,6 +254,7 @@ private: uint16 _remotePort; MessageBuffer _readBuffer; + std::queue<MessageBuffer> _writeQueue; std::atomic<bool> _closed; std::atomic<bool> _closing; diff --git a/src/server/shared/Networking/SocketMgr.h b/src/server/shared/Networking/SocketMgr.h index ce5bc2d8fc2..e479cd2450d 100644 --- a/src/server/shared/Networking/SocketMgr.h +++ b/src/server/shared/Networking/SocketMgr.h @@ -19,7 +19,6 @@ #define SocketMgr_h__ #include "AsyncAcceptor.h" -#include "Config.h" #include "Errors.h" #include "NetworkThread.h" #include <boost/asio/ip/tcp.hpp> @@ -33,18 +32,12 @@ class SocketMgr public: virtual ~SocketMgr() { - delete[] _threads; + ASSERT(!_threads && !_acceptor && !_threadCount, "StopNetwork must be called prior to SocketMgr destruction"); } - virtual bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port) + virtual bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount) { - _threadCount = sConfigMgr->GetIntDefault("Network.Threads", 1); - - if (_threadCount <= 0) - { - TC_LOG_ERROR("misc", "Network.Threads is wrong in your config file"); - return false; - } + ASSERT(threadCount > 0); try { @@ -56,6 +49,7 @@ public: return false; } + _threadCount = threadCount; _threads = CreateThreads(); ASSERT(_threads); @@ -68,11 +62,19 @@ public: virtual void StopNetwork() { + _acceptor->Close(); + if (_threadCount != 0) for (int32 i = 0; i < _threadCount; ++i) _threads[i].Stop(); Wait(); + + delete _acceptor; + _acceptor = nullptr; + delete[] _threads; + _threads = nullptr; + _threadCount = 0; } void Wait() @@ -82,20 +84,14 @@ public: _threads[i].Wait(); } - virtual void OnSocketOpen(tcp::socket&& sock) + virtual void OnSocketOpen(tcp::socket&& sock, uint32 threadIndex) { - size_t min = 0; - - for (int32 i = 1; i < _threadCount; ++i) - if (_threads[i].GetConnectionCount() < _threads[min].GetConnectionCount()) - min = i; - try { std::shared_ptr<SocketType> newSocket = std::make_shared<SocketType>(std::move(sock)); newSocket->Start(); - _threads[min].AddSocket(newSocket); + _threads[threadIndex].AddSocket(newSocket); } catch (boost::system::system_error const& err) { @@ -105,6 +101,23 @@ public: int32 GetNetworkThreadCount() const { return _threadCount; } + uint32 SelectThreadWithMinConnections() const + { + uint32 min = 0; + + for (int32 i = 1; i < _threadCount; ++i) + if (_threads[i].GetConnectionCount() < _threads[min].GetConnectionCount()) + min = i; + + return min; + } + + std::pair<tcp::socket*, uint32> GetSocketForAccept() + { + uint32 threadIndex = SelectThreadWithMinConnections(); + return std::make_pair(_threads[threadIndex].GetSocketForAccept(), threadIndex); + } + protected: SocketMgr() : _acceptor(nullptr), _threads(nullptr), _threadCount(1) { diff --git a/src/server/shared/Packets/ByteBuffer.h b/src/server/shared/Packets/ByteBuffer.h index 5ebe5258a44..d24a91ed458 100644 --- a/src/server/shared/Packets/ByteBuffer.h +++ b/src/server/shared/Packets/ByteBuffer.h @@ -23,22 +23,12 @@ #include "Errors.h" #include "ByteConverter.h" #include "Util.h" - -#include <exception> -#include <list> -#include <map> -#include <string> -#include <vector> #include <cstring> -#include <time.h> -#include <cmath> -#include <type_traits> -#include <boost/asio/buffer.hpp> class MessageBuffer; // Root of ByteBuffer exception hierarchy -class ByteBufferException : public std::exception +class TC_SHARED_API ByteBufferException : public std::exception { public: ~ByteBufferException() throw() { } @@ -52,7 +42,7 @@ private: std::string msg_; }; -class ByteBufferPositionException : public ByteBufferException +class TC_SHARED_API ByteBufferPositionException : public ByteBufferException { public: ByteBufferPositionException(bool add, size_t pos, size_t size, size_t valueSize); @@ -60,7 +50,7 @@ public: ~ByteBufferPositionException() throw() { } }; -class ByteBufferSourceException : public ByteBufferException +class TC_SHARED_API ByteBufferSourceException : public ByteBufferException { public: ByteBufferSourceException(size_t pos, size_t size, size_t valueSize); @@ -68,7 +58,7 @@ public: ~ByteBufferSourceException() throw() { } }; -class ByteBuffer +class TC_SHARED_API ByteBuffer { public: const static size_t DEFAULT_SIZE = 0x1000; @@ -628,15 +618,4 @@ inline void ByteBuffer::read_skip<std::string>() read_skip<char*>(); } -namespace boost -{ - namespace asio - { - inline const_buffers_1 buffer(ByteBuffer const& packet) - { - return buffer(packet.contents(), packet.size()); - } - } -} - #endif diff --git a/src/server/shared/Realm/Realm.cpp b/src/server/shared/Realm/Realm.cpp new file mode 100644 index 00000000000..11c52f281a9 --- /dev/null +++ b/src/server/shared/Realm/Realm.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "Realm.h" + +ip::tcp::endpoint Realm::GetAddressForClient(ip::address const& clientAddr) const +{ + ip::address realmIp; + + // Attempt to send best address for client + if (clientAddr.is_loopback()) + { + // Try guessing if realm is also connected locally + if (LocalAddress.is_loopback() || ExternalAddress.is_loopback()) + realmIp = clientAddr; + else + { + // Assume that user connecting from the machine that bnetserver is located on + // has all realms available in his local network + realmIp = LocalAddress; + } + } + else + { + if (clientAddr.is_v4() && + (clientAddr.to_v4().to_ulong() & LocalSubnetMask.to_v4().to_ulong()) == + (LocalAddress.to_v4().to_ulong() & LocalSubnetMask.to_v4().to_ulong())) + { + realmIp = LocalAddress; + } + else + realmIp = ExternalAddress; + } + + ip::tcp::endpoint endpoint(realmIp, Port); + + // Return external IP + return endpoint; +} diff --git a/src/server/shared/Realm/Realm.h b/src/server/shared/Realm/Realm.h new file mode 100644 index 00000000000..241ccd2bca8 --- /dev/null +++ b/src/server/shared/Realm/Realm.h @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef Realm_h__ +#define Realm_h__ + +#include "Common.h" +#include <boost/asio/ip/address.hpp> +#include <boost/asio/ip/tcp.hpp> + +using namespace boost::asio; + +enum RealmFlags +{ + REALM_FLAG_NONE = 0x00, + REALM_FLAG_VERSION_MISMATCH = 0x01, + REALM_FLAG_OFFLINE = 0x02, + REALM_FLAG_SPECIFYBUILD = 0x04, + REALM_FLAG_UNK1 = 0x08, + REALM_FLAG_UNK2 = 0x10, + REALM_FLAG_RECOMMENDED = 0x20, + REALM_FLAG_NEW = 0x40, + REALM_FLAG_FULL = 0x80 +}; + +struct TC_SHARED_API RealmHandle +{ + RealmHandle() : Realm(0) { } + RealmHandle(uint32 index) : Realm(index) { } + + uint32 Realm; // primary key in `realmlist` table + + bool operator<(RealmHandle const& r) const + { + return Realm < r.Realm; + } +}; + +/// Type of server, this is values from second column of Cfg_Configs.dbc +enum RealmType +{ + REALM_TYPE_NORMAL = 0, + REALM_TYPE_PVP = 1, + REALM_TYPE_NORMAL2 = 4, + REALM_TYPE_RP = 6, + REALM_TYPE_RPPVP = 8, + + MAX_CLIENT_REALM_TYPE = 14, + + REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries + // replaced by REALM_PVP in realm list +}; + +// Storage object for a realm +struct TC_SHARED_API Realm +{ + RealmHandle Id; + uint32 Build; + ip::address ExternalAddress; + ip::address LocalAddress; + ip::address LocalSubnetMask; + uint16 Port; + std::string Name; + uint8 Type; + RealmFlags Flags; + uint8 Timezone; + AccountTypes AllowedSecurityLevel; + float PopulationLevel; + + ip::tcp::endpoint GetAddressForClient(ip::address const& clientAddr) const; +}; + +#endif // Realm_h__ diff --git a/src/server/authserver/Realms/RealmList.cpp b/src/server/shared/Realm/RealmList.cpp index 53aeff6133b..e941800cd76 100644 --- a/src/server/authserver/Realms/RealmList.cpp +++ b/src/server/shared/Realm/RealmList.cpp @@ -16,74 +16,78 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include <boost/asio/ip/tcp.hpp> -#include "Common.h" #include "RealmList.h" #include "Database/DatabaseEnv.h" +#include "Util.h" -namespace boost { namespace asio { namespace ip { class address; } } } +RealmList::RealmList() : _updateInterval(0), _updateTimer(nullptr), _resolver(nullptr) +{ +} -RealmList::RealmList() : m_UpdateInterval(0), m_NextUpdateTime(time(NULL)), _resolver(nullptr) { } RealmList::~RealmList() { - delete _resolver; + delete _updateTimer; +} + +RealmList* RealmList::Instance() +{ + static RealmList instance; + return &instance; } // Load the realm list from the database void RealmList::Initialize(boost::asio::io_service& ioService, uint32 updateInterval) { + _updateInterval = updateInterval; + _updateTimer = new boost::asio::deadline_timer(ioService); _resolver = new boost::asio::ip::tcp::resolver(ioService); - m_UpdateInterval = updateInterval; // Get the content of the realmlist table in the database - UpdateRealms(true); + UpdateRealms(boost::system::error_code()); } -void RealmList::UpdateRealm(uint32 id, const std::string& name, ip::address const& address, ip::address const& localAddr, - ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population, uint32 build) +void RealmList::Close() { - // Create new if not exist or update existed - Realm& realm = m_realms[name]; - - realm.m_ID = id; - realm.name = name; - realm.icon = icon; - realm.flag = flag; - realm.timezone = timezone; - realm.allowedSecurityLevel = allowedSecurityLevel; - realm.populationLevel = population; - - // Append port to IP address. + _updateTimer->cancel(); +} +void RealmList::UpdateRealm(RealmHandle const& id, uint32 build, const std::string& name, ip::address const& address, ip::address const& localAddr, + ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, + float population) +{ + // Create new if not exist or update existed + Realm& realm = _realms[id]; + + realm.Id = id; + realm.Build = build; + realm.Name = name; + realm.Type = icon; + realm.Flags = flag; + realm.Timezone = timezone; + realm.AllowedSecurityLevel = allowedSecurityLevel; + realm.PopulationLevel = population; realm.ExternalAddress = address; realm.LocalAddress = localAddr; realm.LocalSubnetMask = localSubmask; - realm.port = port; - realm.gamebuild = build; + realm.Port = port; } -void RealmList::UpdateIfNeed() +void RealmList::UpdateRealms(boost::system::error_code const& error) { - // maybe disabled or updated recently - if (!m_UpdateInterval || m_NextUpdateTime > time(NULL)) + if (error) return; - m_NextUpdateTime = time(NULL) + m_UpdateInterval; - - // Clears Realm list - m_realms.clear(); - - // Get the content of the realmlist table in the database - UpdateRealms(); -} - -void RealmList::UpdateRealms(bool init) -{ - TC_LOG_INFO("server.authserver", "Updating Realm List..."); + TC_LOG_DEBUG("server.authserver", "Updating Realm List..."); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST); PreparedQueryResult result = LoginDatabase.Query(stmt); + std::map<RealmHandle, std::string> existingRealms; + for (auto const& p : _realms) + existingRealms[p.first] = p.second.Name; + + _realms.clear(); + // Circle through results and add them to the realm map if (result) { @@ -102,8 +106,8 @@ void RealmList::UpdateRealms(bool init) boost::asio::ip::tcp::resolver::iterator endPoint = _resolver->resolve(externalAddressQuery, ec); if (endPoint == end || ec) { - TC_LOG_ERROR("server.authserver", "Could not resolve address %s", fields[2].GetString().c_str()); - return; + TC_LOG_ERROR("server.authserver", "Could not resolve address %s for realm \"%s\" id %u", fields[2].GetString().c_str(), name.c_str(), realmId); + continue; } ip::address externalAddress = (*endPoint).endpoint().address(); @@ -112,8 +116,8 @@ void RealmList::UpdateRealms(bool init) endPoint = _resolver->resolve(localAddressQuery, ec); if (endPoint == end || ec) { - TC_LOG_ERROR("server.authserver", "Could not resolve address %s", fields[3].GetString().c_str()); - return; + TC_LOG_ERROR("server.authserver", "Could not resolve localAddress %s for realm \"%s\" id %u", fields[3].GetString().c_str(), name.c_str(), realmId); + continue; } ip::address localAddress = (*endPoint).endpoint().address(); @@ -122,25 +126,35 @@ void RealmList::UpdateRealms(bool init) endPoint = _resolver->resolve(localSubmaskQuery, ec); if (endPoint == end || ec) { - TC_LOG_ERROR("server.authserver", "Could not resolve address %s", fields[4].GetString().c_str()); - return; + TC_LOG_ERROR("server.authserver", "Could not resolve localSubnetMask %s for realm \"%s\" id %u", fields[4].GetString().c_str(), name.c_str(), realmId); + continue; } ip::address localSubmask = (*endPoint).endpoint().address(); uint16 port = fields[5].GetUInt16(); uint8 icon = fields[6].GetUInt8(); + if (icon == REALM_TYPE_FFA_PVP) + icon = REALM_TYPE_PVP; + if (icon >= MAX_CLIENT_REALM_TYPE) + icon = REALM_TYPE_NORMAL; RealmFlags flag = RealmFlags(fields[7].GetUInt8()); uint8 timezone = fields[8].GetUInt8(); uint8 allowedSecurityLevel = fields[9].GetUInt8(); float pop = fields[10].GetFloat(); uint32 build = fields[11].GetUInt32(); - UpdateRealm(realmId, name, externalAddress, localAddress, localSubmask, port, icon, flag, timezone, - (allowedSecurityLevel <= SEC_ADMINISTRATOR ? AccountTypes(allowedSecurityLevel) : SEC_ADMINISTRATOR), pop, build); + RealmHandle id{ realmId }; - if (init) - TC_LOG_INFO("server.authserver", "Added realm \"%s\" at %s:%u.", name.c_str(), m_realms[name].ExternalAddress.to_string().c_str(), port); + UpdateRealm(id, build, name, externalAddress, localAddress, localSubmask, port, icon, flag, + timezone, (allowedSecurityLevel <= SEC_ADMINISTRATOR ? AccountTypes(allowedSecurityLevel) : SEC_ADMINISTRATOR), pop); + + if (!existingRealms.count(id)) + TC_LOG_INFO("server.authserver", "Added realm \"%s\" at %s:%u.", name.c_str(), externalAddress.to_string().c_str(), port); + else + TC_LOG_DEBUG("server.authserver", "Updating realm \"%s\" at %s:%u.", name.c_str(), externalAddress.to_string().c_str(), port); + + existingRealms.erase(id); } catch (std::exception& ex) { @@ -150,4 +164,22 @@ void RealmList::UpdateRealms(bool init) } while (result->NextRow()); } + + for (auto itr = existingRealms.begin(); itr != existingRealms.end(); ++itr) + TC_LOG_INFO("server.authserver", "Removed realm \"%s\".", itr->second.c_str()); + + if (_updateInterval) + { + _updateTimer->expires_from_now(boost::posix_time::seconds(_updateInterval)); + _updateTimer->async_wait(std::bind(&RealmList::UpdateRealms, this, std::placeholders::_1)); + } +} + +Realm const* RealmList::GetRealm(RealmHandle const& id) const +{ + auto itr = _realms.find(id); + if (itr != _realms.end()) + return &itr->second; + + return NULL; } diff --git a/src/server/shared/Realm/RealmList.h b/src/server/shared/Realm/RealmList.h new file mode 100644 index 00000000000..3b81337e762 --- /dev/null +++ b/src/server/shared/Realm/RealmList.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> + * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +#ifndef _REALMLIST_H +#define _REALMLIST_H + +#include "Common.h" +#include "Realm/Realm.h" +#include <boost/asio/ip/address.hpp> +#include <boost/asio/ip/tcp.hpp> +#include <boost/asio/io_service.hpp> +#include <boost/asio/deadline_timer.hpp> + +using namespace boost::asio; + +/// Storage object for the list of realms on the server +class TC_SHARED_API RealmList +{ +public: + typedef std::map<RealmHandle, Realm> RealmMap; + + static RealmList* Instance(); + + ~RealmList(); + + void Initialize(boost::asio::io_service& ioService, uint32 updateInterval); + void Close(); + + RealmMap const& GetRealms() const { return _realms; } + Realm const* GetRealm(RealmHandle const& id) const; + +private: + RealmList(); + + void UpdateRealms(boost::system::error_code const& error); + void UpdateRealm(RealmHandle const& id, uint32 build, const std::string& name, ip::address const& address, ip::address const& localAddr, + ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population); + + RealmMap _realms; + uint32 _updateInterval; + boost::asio::deadline_timer* _updateTimer; + boost::asio::ip::tcp::resolver* _resolver; +}; + +#define sRealmList RealmList::Instance() +#endif diff --git a/src/server/worldserver/CMakeLists.txt b/src/server/worldserver/CMakeLists.txt index 535383ac605..0de8d6054f3 100644 --- a/src/server/worldserver/CMakeLists.txt +++ b/src/server/worldserver/CMakeLists.txt @@ -8,113 +8,29 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -file(GLOB_RECURSE sources_CommandLine CommandLine/*.cpp CommandLine/*.h) -file(GLOB_RECURSE sources_RemoteAccess RemoteAccess/*.cpp RemoteAccess/*.h) -file(GLOB_RECURSE sources_TCSoap TCSoap/*.cpp TCSoap/*.h) -file(GLOB sources_localdir *.cpp *.h) - -if (USE_COREPCH) - set(worldserver_PCH_HDR PrecompiledHeaders/worldPCH.h) - set(worldserver_PCH_SRC PrecompiledHeaders/worldPCH.cpp) -endif() - -set(worldserver_SRCS - ${worldserver_SRCS} - ${sources_CommandLine} - ${sources_RemoteAccess} - ${sources_TCSoap} - ${sources_localdir} -) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) if( WIN32 ) - set(worldserver_SRCS - ${worldserver_SRCS} - ${sources_windows_Debugging} - ) + list(APPEND PRIVATE_SOURCES ${sources_windows}) if ( MSVC ) - set(worldserver_SRCS - ${worldserver_SRCS} - worldserver.rc - ) + list(APPEND PRIVATE_SOURCES worldserver.rc) endif() endif() -include_directories( - ${CMAKE_BINARY_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/CommandLine - ${CMAKE_CURRENT_SOURCE_DIR}/RemoteAccess - ${CMAKE_CURRENT_SOURCE_DIR}/TCSoap - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/gsoap - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour/Include - ${CMAKE_SOURCE_DIR}/src/common/ - ${CMAKE_SOURCE_DIR}/src/common/Collision - ${CMAKE_SOURCE_DIR}/src/common/Collision/Models - ${CMAKE_SOURCE_DIR}/src/common/Configuration - ${CMAKE_SOURCE_DIR}/src/common/Cryptography - ${CMAKE_SOURCE_DIR}/src/common/Cryptography/Authentication - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Logging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/authserver/Realms - ${CMAKE_SOURCE_DIR}/src/server/database/ - ${CMAKE_SOURCE_DIR}/src/server/database/Database - ${CMAKE_SOURCE_DIR}/src/server/database/Logging - ${CMAKE_SOURCE_DIR}/src/server/game - ${CMAKE_SOURCE_DIR}/src/server/game/Accounts - ${CMAKE_SOURCE_DIR}/src/server/game/Addons - ${CMAKE_SOURCE_DIR}/src/server/game/Battlegrounds - ${CMAKE_SOURCE_DIR}/src/server/game/Chat - ${CMAKE_SOURCE_DIR}/src/server/game/Combat - ${CMAKE_SOURCE_DIR}/src/server/game/Conditions - ${CMAKE_SOURCE_DIR}/src/server/game/DataStores - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Corpse - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Creature - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/DynamicObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/GameObject - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Item/Container - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Object/Updates - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Unit - ${CMAKE_SOURCE_DIR}/src/server/game/Entities/Vehicle - ${CMAKE_SOURCE_DIR}/src/server/game/Globals - ${CMAKE_SOURCE_DIR}/src/server/game/Grids - ${CMAKE_SOURCE_DIR}/src/server/game/Grids/Cells - ${CMAKE_SOURCE_DIR}/src/server/game/Handlers - ${CMAKE_SOURCE_DIR}/src/server/game/Instances - ${CMAKE_SOURCE_DIR}/src/server/game/Loot - ${CMAKE_SOURCE_DIR}/src/server/game/Mails - ${CMAKE_SOURCE_DIR}/src/server/game/Maps - ${CMAKE_SOURCE_DIR}/src/server/game/Miscellaneous - ${CMAKE_SOURCE_DIR}/src/server/game/Movement - ${CMAKE_SOURCE_DIR}/src/server/game/Movement/Waypoints - ${CMAKE_SOURCE_DIR}/src/server/game/Quests - ${CMAKE_SOURCE_DIR}/src/server/game/Scripting - ${CMAKE_SOURCE_DIR}/src/server/game/Server - ${CMAKE_SOURCE_DIR}/src/server/game/Server/Protocol - ${CMAKE_SOURCE_DIR}/src/server/game/Spells/Auras - ${CMAKE_SOURCE_DIR}/src/server/game/Weather - ${CMAKE_SOURCE_DIR}/src/server/game/World - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/shared/DataStores - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic - ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic/LinkedReference - ${CMAKE_SOURCE_DIR}/src/server/shared/Networking - ${CMAKE_SOURCE_DIR}/src/server/shared/Packets - ${CMAKE_SOURCE_DIR}/src/server/shared/Service - ${MYSQL_INCLUDE_DIR} - ${OPENSSL_INCLUDE_DIR} - ${VALGRIND_INCLUDE_DIR} -) +if (USE_COREPCH) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/worldPCH.h) + set(PRIVATE_PCH_SOURCE PrecompiledHeaders/worldPCH.cpp) +endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) add_executable(worldserver - ${worldserver_SRCS} - ${worldserver_PCH_SRC} + ${PRIVATE_PCH_SOURCE} + ${PRIVATE_SOURCES} ) if( NOT WIN32 ) @@ -130,24 +46,33 @@ endif() set_target_properties(worldserver PROPERTIES LINK_FLAGS "${worldserver_LINK_FLAGS}") target_link_libraries(worldserver - game - common - shared - database - scripts - g3dlib - gsoap - Detour - format - ${JEMALLOC_LIBRARY} - ${READLINE_LIBRARY} - ${TERMCAP_LIBRARY} - ${MYSQL_LIBRARY} - ${OPENSSL_LIBRARIES} - ${ZLIB_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ${Boost_LIBRARIES} -) + PUBLIC + scripts + game + gsoap + readline) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) + +target_include_directories(worldserver + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(worldserver + PROPERTIES + FOLDER + "server") + +# Add all dynamic projects as dependency to the worldserver +if (WORLDSERVER_DYNAMIC_SCRIPT_MODULES_DEPENDENCIES) + add_dependencies(worldserver ${WORLDSERVER_DYNAMIC_SCRIPT_MODULES_DEPENDENCIES}) +endif() if( WIN32 ) if ( MSVC ) @@ -173,5 +98,5 @@ endif() # Generate precompiled header if( USE_COREPCH ) - add_cxx_pch(worldserver ${worldserver_PCH_HDR} ${worldserver_PCH_SRC}) + add_cxx_pch(worldserver ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) endif() diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index 53c5f250851..0241221a2ac 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -24,6 +24,7 @@ #include <openssl/crypto.h> #include <boost/asio/io_service.hpp> #include <boost/asio/deadline_timer.hpp> +#include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> #include "Common.h" @@ -34,12 +35,13 @@ #include "OpenSSLCrypto.h" #include "ProcessPriority.h" #include "BigNumber.h" -#include "RealmList.h" #include "World.h" #include "MapManager.h" #include "InstanceSaveMgr.h" #include "ObjectAccessor.h" #include "ScriptMgr.h" +#include "ScriptReloadMgr.h" +#include "ScriptLoader.h" #include "OutdoorPvP/OutdoorPvPMgr.h" #include "BattlegroundMgr.h" #include "TCSoap.h" @@ -47,10 +49,13 @@ #include "GitRevision.h" #include "WorldSocket.h" #include "WorldSocketMgr.h" +#include "Realm/Realm.h" #include "DatabaseLoader.h" #include "AppenderDB.h" +#include "Metric.h" using namespace boost::program_options; +namespace fs = boost::filesystem; #ifndef _TRINITY_CORE_CONFIG #define _TRINITY_CORE_CONFIG "worldserver.conf" @@ -78,11 +83,6 @@ uint32 _worldLoopCounter(0); uint32 _lastChangeMsTime(0); uint32 _maxCoreStuckTimeInMs(0); -WorldDatabaseWorkerPool WorldDatabase; ///< Accessor to the world database -CharacterDatabaseWorkerPool CharacterDatabase; ///< Accessor to the character database -LoginDatabaseWorkerPool LoginDatabase; ///< Accessor to the realm/login database -uint32 realmID; ///< Id of the realm - void SignalHandler(const boost::system::error_code& error, int signalNumber); void FreezeDetectorHandler(const boost::system::error_code& error); AsyncAcceptor* StartRaSocketAcceptor(boost::asio::io_service& ioService); @@ -92,12 +92,15 @@ void WorldUpdateLoop(); void ClearOnlineAccounts(); void ShutdownCLIThread(std::thread* cliThread); void ShutdownThreadPool(std::vector<std::thread>& threadPool); -variables_map GetConsoleArguments(int argc, char** argv, std::string& cfg_file, std::string& cfg_service); +bool LoadRealmInfo(); +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& cfg_service); /// Launch the Trinity server extern int main(int argc, char** argv) { - std::string configFile = _TRINITY_CORE_CONFIG; + signal(SIGABRT, &Trinity::AbortHandler); + + auto configFile = fs::absolute(_TRINITY_CORE_CONFIG); std::string configService; auto vm = GetConsoleArguments(argc, argv, configFile, configService); @@ -115,7 +118,9 @@ extern int main(int argc, char** argv) #endif std::string configError; - if (!sConfigMgr->LoadInitial(configFile, configError)) + if (!sConfigMgr->LoadInitial(configFile.generic_string(), + std::vector<std::string>(argv, argv + argc), + configError)) { printf("Error in config file: %s\n", configError.c_str()); return 1; @@ -136,7 +141,7 @@ extern int main(int argc, char** argv) TC_LOG_INFO("server.worldserver", " \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); TC_LOG_INFO("server.worldserver", " C O R E /\\___/"); TC_LOG_INFO("server.worldserver", "http://TrinityCore.org \\/__/\n"); - TC_LOG_INFO("server.worldserver", "Using configuration file %s.", configFile.c_str()); + TC_LOG_INFO("server.worldserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); TC_LOG_INFO("server.worldserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); @@ -188,9 +193,19 @@ extern int main(int argc, char** argv) } // Set server offline (not connectable) - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = (flag & ~%u) | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, REALM_FLAG_INVALID, realmID); + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realm.Id.Realm); + + LoadRealmInfo(); + + sMetric->Initialize(realm.Name, _ioService, []() + { + TC_METRIC_VALUE("online_players", sWorld->GetPlayerCount()); + }); + + TC_METRIC_EVENT("events", "Worldserver started", ""); // Initialize the World + sScriptMgr->SetScriptLoader(AddScripts); sWorld->SetInitialWorldSettings(); // Launch CliRunnable thread @@ -220,10 +235,20 @@ extern int main(int argc, char** argv) uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD)); std::string worldListener = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); - sWorldSocketMgr.StartNetwork(_ioService, worldListener, worldPort); + int networkThreads = sConfigMgr->GetIntDefault("Network.Threads", 1); + + if (networkThreads <= 0) + { + TC_LOG_ERROR("server.worldserver", "Network.Threads must be greater than 0"); + return false; + } + + sWorldSocketMgr.StartNetwork(_ioService, worldListener, worldPort, networkThreads); // Set server online (allow connecting now) - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_INVALID, realmID); + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_OFFLINE, realm.Id.Realm); + realm.PopulationLevel = 0.0f; + realm.Flags = RealmFlags(realm.Flags & ~uint32(REALM_FLAG_OFFLINE)); // Start the freeze check callback cycle in 5 seconds (cycle itself is 1 sec) if (int coreStuckTime = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0)) @@ -243,6 +268,8 @@ extern int main(int argc, char** argv) // Shutdown starts here ShutdownThreadPool(threadPool); + sLog->SetSynchronous(); + sScriptMgr->OnShutdown(); sWorld->KickAll(); // save and kick all players @@ -257,9 +284,10 @@ extern int main(int argc, char** argv) sOutdoorPvPMgr->Die(); sMapMgr->UnloadAll(); // unload all grids (including locked in memory) sScriptMgr->Unload(); + sScriptReloadMgr->Unload(); // set server offline - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realmID); + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realm.Id.Realm); // Clean up threads if any if (soapThread != nullptr) @@ -275,6 +303,9 @@ extern int main(int argc, char** argv) StopDB(); + TC_METRIC_EVENT("events", "Worldserver shutdown", ""); + sMetric->ForceSend(); + TC_LOG_INFO("server.worldserver", "Halting process..."); ShutdownCLIThread(cliThread); @@ -441,6 +472,59 @@ AsyncAcceptor* StartRaSocketAcceptor(boost::asio::io_service& ioService) return acceptor; } +bool LoadRealmInfo() +{ + boost::asio::ip::tcp::resolver resolver(_ioService); + boost::asio::ip::tcp::resolver::iterator end; + + QueryResult result = LoginDatabase.PQuery("SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE id = %u", realm.Id.Realm); + if (!result) + return false; + + Field* fields = result->Fetch(); + realm.Name = fields[1].GetString(); + boost::asio::ip::tcp::resolver::query externalAddressQuery(ip::tcp::v4(), fields[2].GetString(), ""); + + boost::system::error_code ec; + boost::asio::ip::tcp::resolver::iterator endPoint = resolver.resolve(externalAddressQuery, ec); + if (endPoint == end || ec) + { + TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[2].GetString().c_str()); + return false; + } + + realm.ExternalAddress = (*endPoint).endpoint().address(); + + boost::asio::ip::tcp::resolver::query localAddressQuery(ip::tcp::v4(), fields[3].GetString(), ""); + endPoint = resolver.resolve(localAddressQuery, ec); + if (endPoint == end || ec) + { + TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[3].GetString().c_str()); + return false; + } + + realm.LocalAddress = (*endPoint).endpoint().address(); + + boost::asio::ip::tcp::resolver::query localSubmaskQuery(ip::tcp::v4(), fields[4].GetString(), ""); + endPoint = resolver.resolve(localSubmaskQuery, ec); + if (endPoint == end || ec) + { + TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[4].GetString().c_str()); + return false; + } + + realm.LocalSubnetMask = (*endPoint).endpoint().address(); + + realm.Port = fields[5].GetUInt16(); + realm.Type = fields[6].GetUInt8(); + realm.Flags = RealmFlags(fields[7].GetUInt8()); + realm.Timezone = fields[8].GetUInt8(); + realm.AllowedSecurityLevel = AccountTypes(fields[9].GetUInt8()); + realm.PopulationLevel = fields[10].GetFloat(); + realm.Build = fields[11].GetUInt32(); + return true; +} + /// Initialize connection to the databases bool StartDB() { @@ -449,21 +533,22 @@ bool StartDB() // Load databases DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_NONE); loader - .AddDatabase(WorldDatabase, "World") + .AddDatabase(LoginDatabase, "Login") .AddDatabase(CharacterDatabase, "Character") - .AddDatabase(LoginDatabase, "Login"); + .AddDatabase(WorldDatabase, "World"); if (!loader.Load()) return false; ///- Get the realm Id from the configuration file - realmID = sConfigMgr->GetIntDefault("RealmID", 0); - if (!realmID) + realm.Id.Realm = sConfigMgr->GetIntDefault("RealmID", 0); + if (!realm.Id.Realm) { TC_LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file"); return false; } - TC_LOG_INFO("server.worldserver", "Realm running as realm ID %d", realmID); + + TC_LOG_INFO("server.worldserver", "Realm running as realm ID %d", realm.Id.Realm); ///- Clean the database before starting ClearOnlineAccounts(); @@ -490,7 +575,7 @@ void StopDB() void ClearOnlineAccounts() { // Reset online status for all accounts with characters on the current realm - LoginDatabase.DirectPExecute("UPDATE account SET online = 0 WHERE online > 0 AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = %d)", realmID); + LoginDatabase.DirectPExecute("UPDATE account SET online = 0 WHERE online > 0 AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = %d)", realm.Id.Realm); // Reset online status for all characters CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0"); @@ -501,7 +586,7 @@ void ClearOnlineAccounts() /// @} -variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile, std::string& configService) +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService) { // Silences warning about configService not be used if the OS is not Windows (void)configService; @@ -510,7 +595,8 @@ variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile all.add_options() ("help,h", "print usage message") ("version,v", "print version build info") - ("config,c", value<std::string>(&configFile)->default_value(_TRINITY_CORE_CONFIG), "use <arg> as configuration file") + ("config,c", value<fs::path>(&configFile)->default_value(fs::absolute(_TRINITY_CORE_CONFIG)), + "use <arg> as configuration file") ; #ifdef _WIN32 options_description win("Windows platform specific options"); diff --git a/src/server/worldserver/RemoteAccess/RASession.cpp b/src/server/worldserver/RemoteAccess/RASession.cpp index 59e7b138c48..1ad1ac1dc6c 100644 --- a/src/server/worldserver/RemoteAccess/RASession.cpp +++ b/src/server/worldserver/RemoteAccess/RASession.cpp @@ -121,7 +121,7 @@ bool RASession::CheckAccessLevel(const std::string& user) { std::string safeUser = user; - AccountMgr::normalizeString(safeUser); + Utf8ToUpperOnlyLatin(safeUser); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS); stmt->setString(0, safeUser); @@ -153,10 +153,10 @@ bool RASession::CheckPassword(const std::string& user, const std::string& pass) { std::string safe_user = user; std::transform(safe_user.begin(), safe_user.end(), safe_user.begin(), ::toupper); - AccountMgr::normalizeString(safe_user); + Utf8ToUpperOnlyLatin(safe_user); std::string safe_pass = pass; - AccountMgr::normalizeString(safe_pass); + Utf8ToUpperOnlyLatin(safe_pass); std::transform(safe_pass.begin(), safe_pass.end(), safe_pass.begin(), ::toupper); std::string hash = AccountMgr::CalculateShaPassHash(safe_user, safe_pass); diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist index 217995cb88a..0513f2b0ab4 100644 --- a/src/server/worldserver/worldserver.conf.dist +++ b/src/server/worldserver/worldserver.conf.dist @@ -12,6 +12,7 @@ # SERVER LOGGING # SERVER SETTINGS # UPDATE SETTINGS +# HOTSWAP SETTINGS # WARDEN SETTINGS # PLAYER INTERACTION # CREATURE SETTINGS @@ -33,6 +34,7 @@ # AUCTION HOUSE BOT BUYER CONFIG # LOGGING SYSTEM SETTINGS # PACKET SPOOF PROTECTION SETTINGS +# METRIC SETTINGS # ################################################################################################### @@ -93,6 +95,12 @@ LogsDir = "" # Default: "127.0.0.1;3306;trinity;trinity;auth" - (LoginDatabaseInfo) # "127.0.0.1;3306;trinity;trinity;world" - (WorldDatabaseInfo) # "127.0.0.1;3306;trinity;trinity;characters" - (CharacterDatabaseInfo) +# +# Don't change hostname unless you are hosting mysql on a different machine, if you need help +# with configuration allowing to connect from diferent machine than the one running server +# search for TCE00016 on forum. +# Don't open port on firewall to external connections (it belongs to mysql, not to wow server). +# The username you choose must have permisions to create/alter/rename tables. LoginDatabaseInfo = "127.0.0.1;3306;trinity;trinity;auth" WorldDatabaseInfo = "127.0.0.1;3306;trinity;trinity;world" @@ -161,6 +169,45 @@ BindIP = "0.0.0.0" ThreadPool = 2 # +# CMakeCommand +# Description: The path to your CMake binary. +# If the path is left empty, the built-in CMAKE_COMMAND is used. +# Example: "C:/Program Files (x86)/CMake/bin/cmake.exe" +# "/usr/bin/cmake" +# Default: "" + +CMakeCommand = "" + +# +# BuildDirectory +# Description: The path to your build directory. +# If the path is left empty, the built-in CMAKE_BINARY_DIR is used. +# Example: "../TrinityCore" +# Default: "" + +BuildDirectory = "" + +# +# SourceDirectory +# Description: The path to your TrinityCore source directory. +# If the path is left empty, the built-in CMAKE_SOURCE_DIR is used. +# Example: "../TrinityCore" +# Default: "" + +SourceDirectory = "" + +# +# MySQLExecutable +# Description: The path to your mysql cli binary. +# If the path is left empty, built-in path from cmake is used. +# Example: "C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql.exe" +# "mysql.exe" +# "/usr/bin/mysql" +# Default: "" + +MySQLExecutable = "" + +# ################################################################################################### ################################################################################################### @@ -231,6 +278,25 @@ MaxOverspeedPings = 2 GridUnload = 1 # +# BaseMapLoadAllGrids +# Description: Load all grids for base maps upon load. Requires GridUnload to be 0. +# This will take around 5GB of ram upon server load, and will take some time +# to initially load the server. +# Default: 0 - (Don't pre-load all base maps, dynamically load as used) +# 1 - (Preload all grids in all base maps upon load) + +BaseMapLoadAllGrids = 0 + +# +# InstanceMapLoadAllGrids +# Description: Load all grids for instance maps upon load. Requires GridUnload to be 0. +# Upon loading an instance map, all creatures/objects in the map will be pre-loaded +# Default: 0 - (Don't pre-load all base maps, dynamically load as used) +# 1 - (Preload all grids in the instance upon load) + +InstanceMapLoadAllGrids = 0 + +# # SocketTimeOutTime # Description: Time (in milliseconds) after which a connection being idle on the character # selection screen is disconnected. @@ -291,6 +357,13 @@ PlayerSave.Stats.MinLevel = 0 PlayerSave.Stats.SaveOnlyOnLogout = 1 # +# DisconnectToleranceInterval +# Description: Tolerance (in seconds) for disconnected players before reentering the queue. +# Default: 0 (disabled) + +DisconnectToleranceInterval = 0 + +# # mmap.enablePathFinding # Description: Enable/Disable pathfinding using mmaps - recommended. # Default: 0 - (Disabled) @@ -659,7 +732,7 @@ CharacterCreating.Disabled.RaceMask = 0 # 2 - (Disabled, Paladin) # 4 - (Disabled, Hunter) # 8 - (Disabled, Rogue) -# 16 - (Disabled, Undead) +# 16 - (Disabled, Priest) # 32 - (Disabled, Death Knight) # 64 - (Disabled, Shaman) # 128 - (Disabled, Mage) @@ -1061,9 +1134,8 @@ BeepAtStart = 1 # # Motd -# Description: Message of the Day, displayed at login. -# Use '@' for a newline and be sure to escape special characters. -# Example: "Welcome to John\'s Server@This server runs on Trinity Core." +# Description: Message of the Day, displayed at login. Use '@' for a newline. +# Example: "Welcome to John's Server!@This server is proud to be powered by Trinity Core." # Default: "Welcome to a Trinity Core server." Motd = "Welcome to a Trinity Core server." @@ -1167,26 +1239,6 @@ BirthdayTime = 1222964635 Updates.EnableDatabases = 7 # -# Updates.SourcePath -# Description: The path to your TrinityCore source directory. -# If the path is left empty, built-in CMAKE_SOURCE_DIR is used. -# Example: "../TrinityCore" -# Default: "" - -Updates.SourcePath = "" - -# -# Updates.MySqlCLIPath -# Description: The path to your mysql cli binary. -# If the path is left empty, built-in path from cmake is used. -# Example: "C:/Program Files/MySQL/MySQL Server 5.6/bin/mysql.exe" -# "mysql.exe" -# "/usr/bin/mysql" -# Default: "" - -Updates.MySqlCLIPath = "" - -# # Updates.AutoSetup # Description: Auto populate empty databases. # Default: 1 - (Enabled) @@ -1236,6 +1288,78 @@ Updates.CleanDeadRefMaxCount = 3 ################################################################################################### ################################################################################################### +# HOTSWAP SETTINGS +# +# HotSwap.Enabled (Requires compilation with DYNAMIC_LINKING=1) +# Description: Enables dynamic script hotswapping. +# Reloads scripts on changes. +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.Enabled = 1 + +# +# HotSwap.ScriptDir +# Description: Directory containing the script shared libraries (.dll/.so). +# Example: "/usr/local/scripts" +# Default: "scripts" + +HotSwap.ScriptDir = "scripts" + +# HotSwap.EnableReCompiler +# Description: Enables the dynamic script recompiler. +# Watches your script source directories and recompiles the +# script modules on changes. +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.EnableReCompiler = 1 + +# HotSwap.EnableEarlyTermination +# Description: Terminate the build of a module when an associated +# source file was changed meanwhile. +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.EnableEarlyTermination = 1 + +# HotSwap.EnableBuildFileRecreation +# Description: Recreate build files when sources to a module +# were added or removed. +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.EnableBuildFileRecreation = 1 + +# +# HotSwap.EnableInstall +# Description: Enables cmake install after automatic builds have finished +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.EnableInstall = 1 + +# +# HotSwap.EnablePrefixCorrection +# Description: Allows the core to automatic set the CMAKE_INSTALL_PREFIX +# to it's current location in the filesystem. +# Default: 1 - (Enabled) +# 0 - (Disabled) + +HotSwap.EnablePrefixCorrection = 1 + +# HotSwap.ReCompilerBuildType +# Description: Defines the build type of the builds invoked by the recompiler. +# Default: "" - Built-in build type of the module is used. +# "Release" - Release builds only +# "Debug" - Debug builds only + +HotSwap.ReCompilerBuildType = "" + +# +################################################################################################### + +################################################################################################### # WARDEN SETTINGS # # Warden.Enabled @@ -1354,10 +1478,11 @@ AllowTwoSide.Trade = 0 # # TalentsInspecting -# Description: Allow inspecting characters from the opposing faction. -# Doesn't affect characters in gamemaster mode. -# Default: 1 - (Enabled) -# 0 - (Disabled) +# Description: Allow/disallow inspecting other characters' talents. +# Doesn't affect game master accounts. +# 2 - (Enabled for all characters) +# Default: 1 - (Enabled for characters of the same faction) +# 0 - (Talent inspecting is disabled) TalentsInspecting = 1 @@ -1540,6 +1665,14 @@ ListenRange.TextEmote = 40 ListenRange.Yell = 300 # +# Creature.MovingStopTimeForPlayer +# Description: Time (in milliseconds) during which creature will not move after +# interaction with player. +# Default: 180000 + +Creature.MovingStopTimeForPlayer = 180000 + +# ################################################################################################### ################################################################################################### @@ -1608,24 +1741,27 @@ Channel.RestrictedLfg = 1 # # ChatLevelReq.Channel -# Description: Level requirement for characters to be able to write in chat channels. -# Default: 1 - -ChatLevelReq.Channel = 1 - -# # ChatLevelReq.Whisper -# Description: Level requirement for characters to be able to whisper other characters. +# ChatLevelReq.Emote +# ChatLevelReq.Say +# ChatLevelReq.Yell +# Description: Level requirement for characters to be able to use chats. # Default: 1 +ChatLevelReq.Channel = 1 ChatLevelReq.Whisper = 1 +ChatLevelReq.Emote = 1 +ChatLevelReq.Say = 1 +ChatLevelReq.Yell = 1 # -# ChatLevelReq.Say -# Description: Level requirement for characters to be able to use say/yell/emote. +# PartyLevelReq +# Description: Minimum level at which players can invite to group, even if they aren't on +# the invitee friends list. (Players who are on that friend list can always +# invite despite having lower level) # Default: 1 -ChatLevelReq.Say = 1 +PartyLevelReq = 1 # # PreserveCustomChannels @@ -1751,6 +1887,13 @@ GM.LowerSecurity = 0 GM.TicketSystem.ChanceOfGMSurvey = 50 # +# GM.ForceShutdownThreshold +# Description: Minimum shutdown time in seconds before 'force' is required if other players are connected. +# Default: 30 + +GM.ForceShutdownThreshold = 30 + +# ################################################################################################### ################################################################################################### @@ -2259,16 +2402,16 @@ Battleground.InvitationType = 0 # Default: 300000 - (Enabled, 5 minutes) # 0 - (Disabled, Not recommended) -BattleGround.PrematureFinishTimer = 300000 +Battleground.PrematureFinishTimer = 300000 # -# BattleGround.PremadeGroupWaitForMatch +# Battleground.PremadeGroupWaitForMatch # Description: Time (in milliseconds) a pre-made group has to wait for matching group of the # other faction. # Default: 1800000 - (Enabled, 30 minutes) # 0 - (Disabled, Not recommended) -BattleGround.PremadeGroupWaitForMatch = 1800000 +Battleground.PremadeGroupWaitForMatch = 1800000 # # Battleground.GiveXPForKills @@ -2311,6 +2454,14 @@ Battleground.RewardLoserHonorFirst = 5 Battleground.RewardLoserHonorLast = 5 # +# Battleground.ReportAFK +# Description: Number of reports needed to kick someone AFK from Battleground. +# Range: 1-9 +# Default: 3 + +Battleground.ReportAFK = 3 + +# ################################################################################################### ################################################################################################### @@ -2895,6 +3046,16 @@ NoGrayAggro.Above = 0 NoGrayAggro.Below = 0 # +# PreventRenameCharacterOnCustomization +# Description: If option is set to 1, player can not rename the character in character customization. +# Applies to all character customization commands. +# Default: 0 - (Disabled, character can be renamed in Character Customization) +# 1 - (Enabled, character can not be renamed in Character Customization) +# + +PreventRenameCharacterOnCustomization = 0 + +# ################################################################################################### ################################################################################################### @@ -2951,6 +3112,27 @@ AuctionHouseBot.MinTime = 1 AuctionHouseBot.MaxTime = 72 # +# AuctionHouseBot.Class.CLASS.Allow.Zero = 0 +# Description: Include items without a sell or buy price. +# Default: 0 - (Disabled) +# 1 - (Enabled) + +AuctionHouseBot.Class.Consumable.Allow.Zero = 0 +AuctionHouseBot.Class.Container.Allow.Zero = 0 +AuctionHouseBot.Class.Weapon.Allow.Zero = 0 +AuctionHouseBot.Class.Gem.Allow.Zero = 0 +AuctionHouseBot.Class.Armor.Allow.Zero = 0 +AuctionHouseBot.Class.Reagent.Allow.Zero = 0 +AuctionHouseBot.Class.Projectile.Allow.Zero = 0 +AuctionHouseBot.Class.TradeGood.Allow.Zero = 0 +AuctionHouseBot.Class.Recipe.Allow.Zero = 0 +AuctionHouseBot.Class.Quiver.Allow.Zero = 0 +AuctionHouseBot.Class.Quest.Allow.Zero = 0 +AuctionHouseBot.Class.Key.Allow.Zero = 0 +AuctionHouseBot.Class.Misc.Allow.Zero = 0 +AuctionHouseBot.Class.Glyph.Allow.Zero = 0 + +# # AuctionHouseBot.Items.Vendor # Description: Include items that can be bought from vendors. # Default: 0 - (Disabled) @@ -3058,6 +3240,27 @@ AuctionHouseBot.Items.Orange.Price.Ratio = 100 AuctionHouseBot.Items.Yellow.Price.Ratio = 100 # +# AuctionHouseBot.Class.CLASS.Price.Ratio +# Description: Percentage by which the price of items sold of each class is incremented / decreased (for all houses) +# Default: 100 - (No change) + +AuctionHouseBot.Class.Consumable.Price.Ratio = 100 +AuctionHouseBot.Class.Container.Price.Ratio = 100 +AuctionHouseBot.Class.Weapon.Price.Ratio = 100 +AuctionHouseBot.Class.Gem.Price.Ratio = 100 +AuctionHouseBot.Class.Armor.Price.Ratio = 100 +AuctionHouseBot.Class.Reagent.Price.Ratio = 100 +AuctionHouseBot.Class.Projectile.Price.Ratio = 100 +AuctionHouseBot.Class.TradeGood.Price.Ratio = 100 +AuctionHouseBot.Class.Generic.Price.Ratio = 100 +AuctionHouseBot.Class.Recipe.Price.Ratio = 100 +AuctionHouseBot.Class.Quiver.Price.Ratio = 100 +AuctionHouseBot.Class.Quest.Price.Ratio = 100 +AuctionHouseBot.Class.Key.Price.Ratio = 100 +AuctionHouseBot.Class.Misc.Price.Ratio = 100 +AuctionHouseBot.Class.Glyph.Price.Ratio = 100 + +# # AuctionHouseBot.Items.ItemLevel.* # Description: Prevent seller from listing items below/above this item level # Default: 0 - (Disabled) @@ -3108,7 +3311,7 @@ AuctionHouseBot.Items.Amount.Yellow = 0 # Armor: 8 # Reagent: 1 # Projectile: 2 -# TradeGod: 10 +# TradeGood: 10 # Generic: 1 # Recipe: 6 # Quiver: 1 @@ -3421,8 +3624,10 @@ Appender.DBErrors=2,2,0,DBErrors.log Logger.root=5,Console Server Logger.server=3,Console Server Logger.commands.gm=3,Console GM +Logger.scripts.hotswap=3,Console Server Logger.sql.sql=5,Console DBErrors Logger.sql.updates=3,Console Server +Logger.mmaps=3,Server #Logger.achievement=3,Console Server #Logger.addon=3,Console Server @@ -3431,6 +3636,7 @@ Logger.sql.updates=3,Console Server #Logger.bg.arena=3,Console Server #Logger.bg.battlefield=3,Console Server #Logger.bg.battleground=3,Console Server +#Logger.bg.reportpvpafk=3,Console Server #Logger.chat.log=3,Console Server #Logger.calendar=3,Console Server #Logger.chat.system=3,Console Server @@ -3523,3 +3729,42 @@ PacketSpoof.BanDuration = 86400 # ################################################################################################### + +################################################################################################### +# METRIC SETTINGS +# +# These settings control the statistics sent to the metric database (currently InfluxDB) +# +# Metric.Enable +# Description: Enables statistics sent to the metric database. +# Default: 0 - (Disabled) +# 1 - (Enabled) + +Metric.Enable = 0 + +# +# Metric.Interval +# Description: Interval between every batch of data sent in seconds +# Default: 10 seconds +# + +Metric.Interval = 10 + +# +# Metric.ConnectionInfo +# Description: Connection settings for metric database (currently InfluxDB). +# Example: "hostname;port;database" +# Default: "127.0.0.1;8086;worldserver" + +Metric.ConnectionInfo = "127.0.0.1;8086;worldserver" + +# +# Metric.OverallStatusInterval +# Description: Interval between every gathering of overall worldserver status data in seconds +# Default: 1 second +# + +Metric.OverallStatusInterval = 1 + +# +################################################################################################### diff --git a/src/tools/map_extractor/CMakeLists.txt b/src/tools/map_extractor/CMakeLists.txt index d0f3e42cef8..c0bd102f8e6 100644 --- a/src/tools/map_extractor/CMakeLists.txt +++ b/src/tools/map_extractor/CMakeLists.txt @@ -9,41 +9,38 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -file(GLOB_RECURSE mapextractor_SRCS *.cpp *.h) - -set(include_Dirs - ${CMAKE_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/dep/cppformat - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/libmpq - ${CMAKE_SOURCE_DIR}/src/common - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_CURRENT_SOURCE_DIR}/loadlib -) - -if( WIN32 ) - set(include_Dirs - ${include_Dirs} - ${CMAKE_SOURCE_DIR}/dep/libmpq/win - ) -endif() - -include_directories(${include_Dirs}) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES) add_executable(mapextractor - ${mapextractor_SRCS} + ${PRIVATE_SOURCES} ) +target_include_directories(mapextractor + PUBLIC + ${CMAKE_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/loadlib) + target_link_libraries(mapextractor - common - format - g3dlib - mpq - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - ${Boost_LIBRARIES} -) + PUBLIC + common + mpq) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES) + +target_include_directories(mapextractor + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(mapextractor + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS mapextractor DESTINATION bin) diff --git a/src/tools/map_extractor/System.cpp b/src/tools/map_extractor/System.cpp index f3a761fd437..9d3dc47bce0 100644 --- a/src/tools/map_extractor/System.cpp +++ b/src/tools/map_extractor/System.cpp @@ -53,12 +53,13 @@ char input_path[MAX_PATH_LENGTH] = "."; // ************************************************** enum Extract { - EXTRACT_MAP = 1, - EXTRACT_DBC = 2 + EXTRACT_MAP = 1, + EXTRACT_DBC = 2, + EXTRACT_CAMERA = 4 }; // Select data for extract -int CONF_extract = EXTRACT_MAP | EXTRACT_DBC; +int CONF_extract = EXTRACT_MAP | EXTRACT_DBC | EXTRACT_CAMERA; // This option allow limit minimum height to some value (Allow save some memory) bool CONF_allow_height_limit = true; float CONF_use_minHeight = -500.0f; @@ -103,7 +104,7 @@ void Usage(char* prg) "%s -[var] [value]\n"\ "-i set input path (max %d characters)\n"\ "-o set output path (max %d characters)\n"\ - "-e extract only MAP(1)/DBC(2) - standard: both(3)\n"\ + "-e extract only MAP(1)/DBC(2)/Camera(4) - standard: all(7)\n"\ "-f height stored as int (less map size but lost some accuracy) 1 by default\n"\ "Example: %s -f 0 -i \"c:\\games\\game\"", prg, MAX_PATH_LENGTH - 1, MAX_PATH_LENGTH - 1, prg); exit(1); @@ -151,7 +152,7 @@ void HandleArgs(int argc, char * arg[]) if(c + 1 < argc) // all ok { CONF_extract=atoi(arg[(c++) + 1]); - if(!(CONF_extract > 0 && CONF_extract < 4)) + if(!(CONF_extract > 0 && CONF_extract < 8)) Usage(arg[0]); } else @@ -1025,6 +1026,56 @@ void ExtractDBCFiles(int locale, bool basicLocale) printf("Extracted %u DBC files\n\n", count); } +void ExtractCameraFiles(int locale, bool basicLocale) +{ + printf("Extracting camera files...\n"); + DBCFile camdbc("DBFilesClient\\CinematicCamera.dbc"); + + if (!camdbc.open()) + { + printf("Unable to open CinematicCamera.dbc. Camera extract aborted.\n"); + return; + } + + // get camera file list from DBC + std::vector<std::string> camerafiles; + size_t cam_count = camdbc.getRecordCount(); + + for (size_t i = 0; i < cam_count; ++i) + { + std::string camFile(camdbc.getRecord(i).getString(1)); + size_t loc = camFile.find(".mdx"); + if (loc != std::string::npos) + camFile.replace(loc, 4, ".m2"); + camerafiles.push_back(std::string(camFile)); + } + + std::string path = output_path; + path += "/Cameras/"; + CreateDir(path); + if (!basicLocale) + { + path += langs[locale]; + path += "/"; + CreateDir(path); + } + + // extract M2s + uint32 count = 0; + for (std::string thisFile : camerafiles) + { + std::string filename = path; + filename += (thisFile.c_str() + strlen("Cameras\\")); + + if (boost::filesystem::exists(filename)) + continue; + + if (ExtractFile(thisFile.c_str(), filename)) + ++count; + } + printf("Extracted %u camera files\n", count); +} + void LoadLocaleMPQFiles(int const locale) { std::string fileName = Trinity::StringFormat("%s/Data/%s/locale-%s.MPQ", input_path, langs[locale], langs[locale]); @@ -1111,6 +1162,19 @@ int main(int argc, char * arg[]) return 0; } + if (CONF_extract & EXTRACT_CAMERA) + { + printf("Using locale: %s\n", langs[FirstLocale]); + + // Open MPQs + LoadLocaleMPQFiles(FirstLocale); + LoadCommonMPQFiles(); + + ExtractCameraFiles(FirstLocale, true); + // Close MPQs + CloseMPQFiles(); + } + if (CONF_extract & EXTRACT_MAP) { printf("Using locale: %s\n", langs[FirstLocale]); diff --git a/src/tools/mmaps_generator/CMakeLists.txt b/src/tools/mmaps_generator/CMakeLists.txt index 4eb416a106b..64c82101f61 100644 --- a/src/tools/mmaps_generator/CMakeLists.txt +++ b/src/tools/mmaps_generator/CMakeLists.txt @@ -8,51 +8,33 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -file(GLOB_RECURSE mmap_gen_sources *.cpp *.h) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES) -set(mmap_gen_Includes - ${CMAKE_BINARY_DIR} - ${CMAKE_SOURCE_DIR}/dep/libmpq - ${CMAKE_SOURCE_DIR}/dep/zlib - ${CMAKE_SOURCE_DIR}/dep/bzip2 - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Recast - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Recast/Include - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour - ${CMAKE_SOURCE_DIR}/dep/recastnavigation/Detour/Include - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/game/Conditions - ${CMAKE_SOURCE_DIR}/src/common - ${CMAKE_SOURCE_DIR}/src/common/Collision - ${CMAKE_SOURCE_DIR}/src/common/Collision/Management - ${CMAKE_SOURCE_DIR}/src/common/Collision/Maps - ${CMAKE_SOURCE_DIR}/src/common/Collision/Models - ${CMAKE_SOURCE_DIR}/src/common/Debugging - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/common/Utilities -) +add_executable(mmaps_generator ${PRIVATE_SOURCES}) -if( WIN32 ) - set(mmap_gen_Includes - ${mmap_gen_Includes} - ${CMAKE_SOURCE_DIR}/dep/libmpq/win - ) -endif() +target_link_libraries(mmaps_generator + PUBLIC + common + Recast + Detour + mpq) -include_directories(${mmap_gen_Includes}) +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES) -add_executable(mmaps_generator ${mmap_gen_sources}) +target_include_directories(mmaps_generator + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) -target_link_libraries(mmaps_generator - common - g3dlib - Recast - Detour - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ${Boost_LIBRARIES} -) +set_target_properties(mmaps_generator + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS mmaps_generator DESTINATION bin) diff --git a/src/tools/mmaps_generator/MapBuilder.cpp b/src/tools/mmaps_generator/MapBuilder.cpp index 3a63f9718db..80b7b266f27 100644 --- a/src/tools/mmaps_generator/MapBuilder.cpp +++ b/src/tools/mmaps_generator/MapBuilder.cpp @@ -699,7 +699,7 @@ namespace MMAP iv.polyMesh = rcAllocPolyMesh(); if (!iv.polyMesh) { - printf("%s alloc iv.polyMesh FIALED!\n", tileString); + printf("%s alloc iv.polyMesh FAILED!\n", tileString); delete[] pmmerge; delete[] dmmerge; delete[] tiles; @@ -710,7 +710,7 @@ namespace MMAP iv.polyMeshDetail = rcAllocPolyMeshDetail(); if (!iv.polyMeshDetail) { - printf("%s alloc m_dmesh FIALED!\n", tileString); + printf("%s alloc m_dmesh FAILED!\n", tileString); delete[] pmmerge; delete[] dmmerge; delete[] tiles; diff --git a/src/tools/vmap4_assembler/CMakeLists.txt b/src/tools/vmap4_assembler/CMakeLists.txt index c33b2996685..58cb066f75b 100644 --- a/src/tools/vmap4_assembler/CMakeLists.txt +++ b/src/tools/vmap4_assembler/CMakeLists.txt @@ -9,17 +9,6 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -include_directories( - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/src/server/shared/Debugging - ${CMAKE_SOURCE_DIR}/src/common - ${CMAKE_SOURCE_DIR}/src/common/Collision - ${CMAKE_SOURCE_DIR}/src/common/Collision/Maps - ${CMAKE_SOURCE_DIR}/src/common/Collision/Models - ${ZLIB_INCLUDE_DIR} -) - add_executable(vmap4assembler VMapAssembler.cpp) if(CMAKE_SYSTEM_NAME MATCHES "Darwin") @@ -28,9 +17,12 @@ endif() target_link_libraries(vmap4assembler common - g3dlib - ${ZLIB_LIBRARIES} -) + zlib) + +set_target_properties(vmap4assembler + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS vmap4assembler DESTINATION bin) diff --git a/src/tools/vmap4_extractor/CMakeLists.txt b/src/tools/vmap4_extractor/CMakeLists.txt index 55e66b32ea8..f13aaec15b2 100644 --- a/src/tools/vmap4_extractor/CMakeLists.txt +++ b/src/tools/vmap4_extractor/CMakeLists.txt @@ -9,28 +9,30 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -file(GLOB_RECURSE sources *.cpp *.h) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES) -set(include_Dirs - ${CMAKE_SOURCE_DIR}/dep/libmpq -) +add_executable(vmap4extractor ${PRIVATE_SOURCES}) -if( WIN32 ) - set(include_Dirs - ${include_Dirs} - ${CMAKE_SOURCE_DIR}/dep/libmpq/win - ) -endif() +target_link_libraries(vmap4extractor + PUBLIC + mpq) -include_directories(${include_Dirs}) +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES) -add_executable(vmap4extractor ${sources}) +target_include_directories(vmap4extractor + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) -target_link_libraries(vmap4extractor - mpq - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} -) +set_target_properties(vmap4extractor + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS vmap4extractor DESTINATION bin) |